【问题标题】:MeteorJS - Differences between function() and () => [duplicate]MeteorJS - 函数()和()之间的差异=> [重复]
【发布时间】:2016-09-03 16:12:05
【问题描述】:

现在我的助手正在使用function()

updateCVId: function() {
    return this._id; //return the real id

}

它工作正常,但如果我使用()=>

updateCVId:()=> {
    return this._id; //return undefined
}

那么 this._id 是未定义的。

事件也是如此:

'click .foo': function(evt, tmp) {
    console.log(this._id); //log the real id
}

'click .foo': (evt, tmp)=> {
    console.log(this._id); //log undefined
}

谁能告诉我如果我使用()=>,如何获取数据?

谢谢你们。

【问题讨论】:

  • 在箭头函数中,this 被指定为创建函数的执行上下文的this。在函数声明或表达式中,它由调用(或 bind)设置,因此很可能是不同的对象。
  • 好的,那么我在普通函数中如何获取箭头函数中的数据?
  • 使用函数声明或表达式(第一个例子),见Do ES6 arrow functions always close over “this”?

标签: javascript meteor ecmascript-6


【解决方案1】:

箭头函数=> 旨在从词法范围自动绑定上下文this。在您的情况下,this 未定义,因为它在 'strict mode' 中运行。

要解决您的问题,您可以:

1) 使用常规函数,就像您已经做过的那样:

var actions = {
   //...
   updateCVId: function() {
      return this._id; //return the real id
   }
   //...
};

2) 使用 ES6 简写函数表示法:

var actions = {
   //...
   updateCVId() {
      return this._id; //return the real id
   }
   //...
};

function() {}=> 之间的区别在于this 上下文以及调用如何影响this

function() {} this 中由调用函数的方式决定。如果将其作为对象上的方法调用,this 将是对象本身:actions.updateCVId()
我称之为soft linked this

在箭头函数情况下,=> this 自动绑定到定义函数的词法范围的this。在您的示例中,它是 undefined,这是 'strict mode' 的默认情况。
不管以后如何调用箭头函数,它都会有thisundefined
我称之为hard linked this

您可以在this article 中找到有关this 关键字的更多详细信息。

【讨论】:

    猜你喜欢
    • 2012-11-21
    • 2012-12-16
    • 2018-07-24
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    相关资源
    最近更新 更多