continuation from the closures notes
Here’s an example of why it’s important to bind this, using our current code:
/* ... previous code */
const dog = {
name: "Fido",
bark: with_counter(() => console.log(`I'm ${this.name}, bau bau!`))
};
dog.bark() // I'm undefined, bau bau!\nFunction was now called 1 time!We ought to change our current code using Function.prototype.bind() (or call(), or apply()…)
function with_counter(callback) {
let counter = 0;
return function () {
callback = callback.bind(this);
callback();
++counter;
console.log(`Function was now called ${counter} time${counter > 1 ? 's' : ''}!`);
}
}
const dog = {
name: "Fido",
bark: with_counter(function() {console.log(`I'm ${this.name}, bau bau!`)})
};
dog.bark(); //I'm Fido, bau bau!\nFunction was now called 1 time!Note the arrow function to normal function change!
to be continued…
