Geeks,
I have the following codes:
Snippet A:
var x = (function(){ this.id="Dog"; return this; }());
var y = (function(){ this.id="Cat"; return this; }());
alert(x.id); //outputs Cat
alert(y.id); //outputs Cat
Snippet B:
var x = (new function(){ this.id="Dog"; });
var y = (new function(){ this.id="Cat"; });
alert(x.id); //ouputs Dog
alert(y.id); //outputs Cat
Why is x replaced by y in Snippet A and not on B?
In the snippet A, on x and y, the
thiskeyword refers to the global object, you are creating setting the value to the same global variable (window.id).In the snippet B, you are using the
newoperator, and the functions are executed as constructor functions, thethiskeyword refers to a newly created object.To avoid that behavior in your snippet A, you can create a new object instance and use it instead of
this:When you call global functions, since they are members of the global object:
Is equivalent to:
And the context inside that function will be the global object itself (
window).