箭头函数使用调用,应用,绑定-不起作用吗? [英] Arrow functions using call, apply, bind - not working?

查看:186
本文介绍了箭头函数使用调用,应用,绑定-不起作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将简单的ES5代码转换为ES6时,我感到有些困惑.

I'm being a bit puzzled when I try to convert a simple ES5 code to ES6.

假设我有以下代码块:

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.

但是,一旦我开始使用const和arrow函数之类的ES6功能,就像这样:

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
}

它不再工作,并引发错误:无法读取未定义的属性"num".

It doesn't work anymore and throws an error: Cannot read property 'num' of undefined.

有人可以解释为什么this不再工作吗?

Can someone please explain why this doesn't work anymore?

推荐答案

Lambda函数(箭头函数)不会创建新的函数上下文,也不会使用调用函数的上下文.

Lambda functions (arrow functions) doesn't create new functional context and use context of a calling function.

因此,"this"是指父上下文.如果没有'num'变量,则为未定义变量.

So "this" refers to a parent context. If there's no 'num' variable than it's undefined.

通常,这真的很方便,因为在大多数情况下,您使用一个上下文而不是在创建的每个函数中都创建一个新上下文.我认为call/apply/bind完全令人困惑,而lambda函数使其变得不必要.

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.

这篇关于箭头函数使用调用,应用,绑定-不起作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆