【问题标题】:This values for arrow functions [duplicate]箭头函数的此值[重复]
【发布时间】:2015-10-17 07:24:54
【问题描述】:

我正在尝试理解 ECMAScript 6 中的箭头函数。

这是我在阅读时遇到的定义:

箭头函数具有隐式this 绑定,这意味着 箭头函数内的this 值是远离的 与箭头作用范围内this的值相同 已定义!

根据定义,我认为arrow functionthis 应该包含与定义箭头函数相同的块级值。

代码:

var test = {
  id: "123123",
  k: {
    laptop: "ramen",
    testfunc: () => console.log(this)
  }
}

console.log(test.k.testfunc);

但是,我从代码中得到了这个结果

function testfunc() {
    return console.log(undefined);
}

我认为我会得到以下输出:

{"laptop": "ramen"}

如果我运行这个

console.log(test.k.testfunc());

【问题讨论】:

  • 在 FF 中使用 console.log( test.k.testfunc() ); 时(注意末尾的括号),我得到了对 window.xml 的引用。在定义函数时这是正确的,在我的情况下,当前范围是 window
  • 这应该有助于解释:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…"this"。看看我在那里做了什么?

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

让我们转换成等效的 ES5 代码:

var test = {
  id: "123123",
  k: {
    laptop: "ramen",
    testfunc: function(){return console.log(this)}.bind(this)
  }
}

请记住,this 取决于您如何调用该函数。外部this 不在函数内部,因此在严格模式下默认为undefined

下面的简化场景:

console.log(this) // undefined

var test = {
  a: this // same `this` as above
}

【讨论】:

  • @natebarbettini 箭头函数从其封闭范围(函数范围)继承“this”,有趣的是,这将起作用 - testfunc: function() { ()=>{console.log(this)} () }
【解决方案2】:

您在定义var test 的同一范围内定义箭头函数。如果您在全局范围内定义test,那么箭头函数的上下文也将是全局范围。

如果您在方法内部定义测试,箭头函数将共享方法的上下文。

function method() {
  const self = this;

  const test = {
    foo: () => console.log(self === this);
  }

  test.foo()
  // console: true
}

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 1970-01-01
    • 2021-03-29
    • 2021-04-22
    • 1970-01-01
    • 2023-03-15
    • 2018-08-02
    • 2015-05-02
    • 2018-07-18
    相关资源
    最近更新 更多