Why does creating inline instances behave differently?

Consider this code:

function Foo() { } Foo.prototype.alert = function() { alert(this); } (new Foo()).alert(); 

When executed (in jsfiddle), a warning indicates that 'this' is a window object. Change last line to:

 var foo = new Foo(); foo.alert(); 

works as expected.

Why is the difference?

+7
source share
2 answers

It seems like you are missing a colon:

 function Foo() { } Foo.prototype.alert = function() { alert(this); }; //Semi-colon here! (new Foo()).alert();​ 

Here's the fiddle in which it works as you expect.

Actually, what happens is that the alert method is called immediately, and a new Foo instance is passed to it, and then the alert is called on the return value (which is undefined ):

 Foo.prototype.alert = function() { alert(this); }(new Foo()).alert(); 

As @Nemoy mentioned, if you just use new Foo().alert() , you will get the expected behavior, because automatic colon insertion will contain a half in the place you want (the lack of a half-column doesn’t change the code value). And since the new operator has the highest priority, parentheses are not required.

+4
source

Your code is actually:

 function Foo() { } Foo.prototype.alert = function() { alert(this); }(new Foo()).alert(); 

Due to the missing semicolon, add a semicolon and it will work properly.

+6
source

All Articles