9

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?

2
  • hey @angular_learner did you get the necessary answer to your question here? If no can you please point out then it would be easier for others to provide a more detailed answer, if yes then please mark it as accepted. Will be helpful for many Commented Jun 16, 2018 at 16:06
  • The answer is not sufficient Commented Dec 15, 2018 at 7:45

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.