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

半腔热情 提交于 2019-12-12 21:24:03

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/43576089/arrow-functions-using-call-apply-bind-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!