I'm reading this article on using ES6 arrow functions. It gives the following example, where you have to use bind(this)
, followed by the corresponding code with arrow functions.
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}.bind(this), 1000);
}
};
It says In the ES5 example, .bind(this) is required to help pass the this context into the function
.
What I Want To Know: Why do you use bind(this)
with the callback to setTimeout
rather than with the counter
function? ie why isn't the above code like this:
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}, 1000);
}.bind(this);
};