Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript? -


both of these code blocks below alert foo bar. difference })() , }()).

code 1:

(function() {     bar = 'bar';     alert('foo'); })();  alert(bar); 

code 2:

(function() {     bar = 'bar';     alert('foo'); }());  alert(bar); 

so there difference, apart syntax?

no; identical


however, if add new beforehand , .something afterwards, different.

code 1

new (function() {     this.prop = 4; }) ().prop; 

this code creates new instance of function's class, gets prop property of new instance.
returns 4.

it's equivalent

function myclass() {     this.prop = 4; } new myclass().prop; 

code 2

new ( function() {     return { class: function() { } };  }() ).class; 

this code calls new on class property.
since parentheses function call inside outer set of parentheses, aren't picked new expression, , instead call function normally, returning return value.
new expression parses .class , instantiates that. (the parentheses after new optional)

it's equivalent to

var namespace = { class: function() { } };  function getnamespace() { return namespace; }  new ( getnamespace() ).class; //or, new namespace.class; 

without parentheses around call getnamespace(), parsed (new getnamespace()).class — call instantiate getnamespace class , return class property of new instance.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -