Reputation: 6613
Here's an example
function banana() {
this.size = 5;
this.say_size = function() {
console.log(this.size);
}.bind(this);
}
banana.prototype.say_size2 = function() {
console.log(this.size);
}
var b = new banana();
b.say_size();
b.say_size2(); //TLDR: why does this line work without binding?
setTimeout(b.say_size, 100);
setTimeout(b.say_size2, 200);
So, in the case I call b.say_size or b.say_size2 directly, 'this' refers to the banana object and I get '5' as output on both.
In case the function is called by a timer or an event though, 'this' is set to window unless the called function is bound to the object.
What I don't understand is how say_size2 gets the right 'this' when called directly without the prototype function being bound to anything?
Upvotes: 0
Views: 43
Reputation: 8715
When you are calling a method on an object, (b.say_size()
or b.say_size2()
) context inside a method points to that object (this === b
).
setTimeout
accepts a function as a first argument, which is executed in global context (this === window
).
For simplicity try to assign a function to a variable and call it:
function banana() {
this.size = 5;
this.say_size = function() {
console.log(this.size);
//}.bind(this); Let's not bind yet
}
}
banana.prototype.say_size2 = function() {
console.log(this.size);
}
var b = new banana();
b.say_size(); // 5 even without binding, instance method
b.say_size2(); // 5, instance method from prototype chain
var foo = b.say_size2;
foo(); // undefined
var bar = b.say_size;
bar(); // undefined
bar = b.say_size.bind(b);
bar(); // 5
In both cases these functions are executed in a global context, however, as b.say_size
was explicitly bound to a different object, JavaScript engine will not force this
to be window
.
How does "this" keyword work within a function?
Upvotes: 1