Consider this code:
function Foo() {
}
Foo.prototype.alert = function() {
alert(this);
}
(new Foo()).alert();
When executed (in jsfiddle), the alert shows that ‘this’ is the window object. Changing the last line to :
var foo = new Foo();
foo.alert();
works as expected.
Why is the difference?
It seems that you are missing a semi-colon:
Here’s a fiddle in which it appears to work as you expect.
What is actually happening is that the
alertmethod gets called immediately, with a new instance ofFoopassed into it, andalertis then called on the return value (which isundefined):As @Nemoy has mentioned, if you just use
new Foo().alert()you will get the expected behaviour because automatic semi-colon insertion will put a semi-colon in the right place for you (the lack of a semi-colon doesn’t change the meaning of the code). And as thenewoperator has the highest precedence, the parentheses are not required.