I'm trying to understand arrow functions at the moment.
I know that with arrow functions the scoping is a bit different. However, I'm still kind of confused on how it all works.
Here's an example that I don't understand all that well.
// ES5
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}.bind(this), 1000);
}
};
Now, here's that exact same code block but with arrow functions used.
// ES6
var obj = {
id: 42,
counter: function counter() {
setTimeout(() => {
console.log(this.id);
}, 1000);
}
};
Looking at it, it seems to me it's all about the levels. Please correct me if I'm wrong, but with ES5 we would use the .bind()
method in this instance because without it, it would return as undefined. I assume this is because in this instance, the this
keyword in console.log(this.id);
is referring to the counter
object and by default, it could not find the id
of the obj
object.
Kind of confusing but I think that's it. Now, with the arrow functions, I'm not sure why console.log(this.id);
would work. Does this mean as long as it's in the same code block, it could be used?
Much appreciation!