Reputation: 10230
Hey guys i have been trying to learn what the bind() method does in JS and i have found a few helpful resources in SO , MDN and also git that do explain this rather well , but i am still a bit confused with a practical example that i found on MDN. The below code i am talking about :
function LateBloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
LateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
};
now bind function just like call() or apply() , thats what i understood so far , but what it does is , it can delay the execution of a function while preserving or rather binding the value of the this
to a specific function .
now in the below lines of code :
LateBloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
what is the 1st this
pointing to ? and what is the secound this
pointing to ?
Upvotes: 2
Views: 123
Reputation: 780724
In this.declare.bind(this)
, the first this
is used to get the current object's declare
method. Then we use bind
to create a new function that will call that method with a specific this
value, and that's the argument to bind()
. It just so happens that we're binding it to the current object, so we use this
in both place, but we don't have to. We could write:
var another = new LateBloomer;
setTimeout(this.declare.bind(another), 1000);
This gets the current object's declare
method, and arranges to call it on another
in 1 second.
Upvotes: 2