箭头功能和这个 [英] arrow function and this

查看:112
本文介绍了箭头功能和这个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览Twitter并发现此推文:

I'm browsing twitter and found this tweet:

https://twitter.com/_ericelliott/status/855598297939144704

以下是推文中的代码:

const double = () => this.x * 2;
const numDouble = double.bind({ x: 5 });
numDouble();

当您在控制台中运行此代码段时,它将生成NaN。
怎么样?
作者显式绑定x的值,但它仍然显示NaN。

When you run this snippet in console it'll produce NaN. How? Author is explicitly binding the value of x, but still it's showing NaN.

作者还指定箭头函数不能绑定它。据我所知,箭头函数在词法上绑定了这个形式围绕范围的值。那么为什么作者要这么说呢?

Author is also specifying that arrow function can't bind this. As i know that arrow function lexically bind the value of this form surrounding scope. Then why author is claiming so?

请澄清我的疑惑,并提前感谢您的帮助。

Please clarify my doubts and Thanks in advance for the help.

推荐答案

箭头函数 不绑定。根据MDN:


没有绑定



直到箭头函数,每个new函数定义了自己的这个
(构造函数中的新对象,在严格模式下未定义
函数调用,上下文对象if该函数被称为
对象方法等)。这被证明是一种令人烦恼的
面向对象的编程风格。

No binding of this

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

所以这个<你的例子中的/ code>将是全局对象窗口,它显然没有名为 x 。

So this in your example will be the global object window which apparently don't have a property called x.

示例:

function foo() {
  let arrow = () => {
    console.log(this);     // will use foo's this as arrow will never have its own this
  }
  
  arrow.call({"x": "x"});  // ... even if we specify it using bind, call, or apply
}

foo.call({"y": "y"});      // specifying the this for foo (this value will eventually be used by arrow because it will be availbale in its scope)

这篇关于箭头功能和这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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