MeteorJS - function()和()=>之间的差异

时间:2016-05-09 06:08:08

标签: javascript meteor ecmascript-6

现在我的助手正在使用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
}

有人可以告诉我,如果我使用()=>,如何获取数据?

谢谢你们。

1 个答案:

答案 0 :(得分:4)

箭头函数=>旨在自动将词汇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关键字的更多详细信息。