Reputation: 8760
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?
Upvotes: 0
Views: 77
Reputation: 116980
The difference between the two is that Snippet B is using a constructor function by prefixing the call with the new
keyword, while snippet A is not. This is the short answer.
The long answer is that although snippet A introduces a new scope on each anonymous function invocation, since it is not being used in a constructor context it's this
variable simply points to the global window
object. So snippet A is equivalent to this:
var x = (function(){ window.id="Dog"; return window; }());
var y = (function(){ window.id="Cat"; return window; }());
Thus, each invocation just clobbers the same [global] variable.
Since snippet B is using the new
keyword, you define and immediately call a constructor function. JavaScript proceeds to initialize the this
variable inside the constructor function to point to a new instance of the [just defined] anonymous function.
You may have seen the new function(){}
idiom some time ago being touted as the best way to define and immediately execute a block of code. Well, it comes with the overhead of JavaScript object instantiation (as you've found), and is not generally used as widely anymore.
Upvotes: 3
Reputation: 827286
In the snippet A, on x and y, the this
keyword 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 new
operator, and the functions are executed as constructor functions, the this
keyword 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
:
var x = (function(){
var instance = {};
instance.id = "Dog";
return instance;
}());
var y = (function(){
var instance = {};
instance.id = "Cat";
return instance;
}());
alert(x.id); //outputs Dog
alert(y.id); //outputs Cat
When you call global functions, since they are members of the global object:
globalFunction();
Is equivalent to:
window.globalFunction();
And the context inside that function will be the global object itself (window
).
Upvotes: 2