Reputation: 429
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!
Upvotes: 2
Views: 270
Reputation: 22275
As everyone says ES6 arrows function don't have a this
so they can use the this
of their "parent".
But there also another différence in ES6 you din't notice: in js objects ,you dont need to use the function
word, as follow
// ES6
var obj = {
id: 42,
counter() {
setTimeout(() => {
console.log(this.id / 7);
}, 1000);
}
};
console.log('start')
obj.counter();
Upvotes: 1
Reputation: 10076
From docs:
An arrow function does not have its own
this
. Thethis
value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching forthis
which is not present in current scope they end up findingthis
from its enclosing scope.
Arrow function is doing exactly what .bind(this)
does. Both your examples are equivalent.
Upvotes: 1
Reputation: 8515
In the first example if you wouldn't use bind()
, then this
would refer to the setTimeout
callback. Because you used .bind()
you changed the this
reference to the obj
object. That's why you got the 42
as this.id
.
In the second example, bind()
is not required because arrow function does not have its own this
, it's the same as the parent this
, so in this case it's pointing to the obj
object and that's why you also get 42
as the this.id
Upvotes: 1