Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow functions using call, apply, bind - not working? [duplicate]

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?

like image 928
angular_learner Avatar asked Dec 18 '22 07:12

angular_learner


1 Answers

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.

like image 98
norekhov Avatar answered Dec 24 '22 03:12

norekhov