I'm being a bit puzzled when I try to convert a simple ES5 code to ES6.
Let's say I have this block of code:
var obj = {num: 2}
var addToThis = function (a, b, c) {
return this.num + a + b + c
}
// call
console.log(addToThis.call(obj, 1, 2, 3))
// apply
const arr = [1, 2, 3]
console.log(addToThis.apply(obj, arr))
// bind
const bound = addToThis.bind(obj)
console.log(bound(1, 2, 3))
Everything above runs smoothly and as expected.
But as soon as I start using ES6 features such as const and arrow function, like this:
const obj = {num: 2}
const addToThis = (a, b, c) => {
return this.num + a + b + c
}
It doesn't work anymore and throws an error: Cannot read property 'num' of undefined.
Can someone please explain why this
doesn't work anymore?
Lambda functions (arrow functions) doesn't create new functional context and use context of a calling function.
So "this" refers to a parent context. If there's no 'num' variable than it's undefined.
Usually it's really convenient because most of the time you use one context instead of creating a new one in every function you create. In my opinion call/apply/bind is completely confusing and lambda functions makes it unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With