javascript - understanding MDN's example of bind -
hey guys have been trying learn bind() method in js , have found few helpful resources in so , mdn , git explain rather , still bit confused practical example found on mdn. below code talking :
function latebloomer() { this.petalcount = math.ceil(math.random() * 12) + 1; } // declare bloom after delay of 1 second latebloomer.prototype.bloom = function() { window.settimeout(this.declare.bind(this), 1000); }; latebloomer.prototype.declare = function() { console.log('i beautiful flower ' + this.petalcount + ' petals!'); };
now bind function call() or apply() , thats understood far , , can delay execution of function while preserving or rather binding value of this
specific function .
now in below lines of code :
latebloomer.prototype.bloom = function() { window.settimeout(this.declare.bind(this), 1000); };
what 1st this
pointing ? , secound this
pointing ?
in this.declare.bind(this)
, first this
used current object's declare
method. use bind
create new function call method specific this
value, , that's argument bind()
. happens we're binding current object, use this
in both place, don't have to. write:
var = new latebloomer; settimeout(this.declare.bind(another), 1000);
this gets current object's declare
method, , arranges call on another
in 1 second.
Comments
Post a Comment