In my lifelong quest to write my entire code on a single line, and give all the psychopathic maintainers nightmares, I ask the following question:
Is there any way I can instantiate an object, assign it to a variable, and call a function on the instantiation on the same line?
Eg I have:
var abc=new window();
window.show()
But i want something along the lines o开发者_开发百科f...
(var abc= new window).show()
Sure. Use an anonymous function to allow you to embed statements inside your expression thus:
var abc = (function (abc) { return abc.show(), abc }(new window));
I think the essence of qour question is: Can you use var
inside an expression?
The answer is No. A var
statement is, well, a statement, and not an expression. The contents of parentheses however need to be expressions.
If you're interested in the technical details, see http://ecma262-5.com/ELS5_HTML_with_CorrectionNotes.htm#AnnexA, A.3 and A.4
Edit: You can however use
var abc;
(abc = new window()).show();
...which is pretty pointless here I guess.
How about?
var abc=new window();abc.show();
Or in one statement
new window().show();
Or using eval()
eval("var abc=new window();abc.show();")
精彩评论