This question already has an answer here:
- When should I use Arrow functions in ECMAScript 6? 9 answers
- Can you bind arrow functions? 8 answers
- Are 'Arrow Functions' and 'Functions' equivalent / exchangeable? 1 answer
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?