Reputation: 179
Consider the following JS object, it has:
When the value of Pipe.x is printed immediately during Object creation, for some reason Pipe.x is undefined
but when P.y() is called, after an object, the Object has been created, the Value of Pipe.x is 100, as it should have been in the first place.
var Pipe = {
x: 100,
p: function(){
console.log('p says x is ' + this.x); // prints y says x is undefined
}(), // call immediately
y: function(){
console.log('y says x is ' + this.x);
}
}
Pipe.y(); // prints y says x is 100
Is there any JS object property I'm missing which makes Pipe.p() print undefined and P.y() print 100?
Upvotes: 2
Views: 99
Reputation: 2133
The this
Context depends on how it is being called.
When you call Pipe.y(), it is equivalent to obj.method() and this
will be pointed to obj, in this case Pipe.
When p is being executed as IIFE, this is set to window and there is no x on window
Upvotes: 5