流星ES6脂肪箭头功能和`this`在onCreated不工作

问题描述:

对不起,ES6福利局这里:流星ES6脂肪箭头功能和`this`在onCreated不工作

Template.hello.onCreated(() => { 
    // counter starts at 0 
    this.counter = new ReactiveVar(0); 
}); 

Template.hello.helpers({ 
    counter() { 
    return Template.instance().counter.get(); 
    }, 
}); 

Template.hello.events({ 
    'click button'(event, instance) { 
    // increment the counter when button is clicked 
    instance.counter.set(instance.counter.get() + 1); 
    }, 
}); 

当我按一下按钮我得到Cannot read property 'get' of undefined

但是当我做

Template.hello.onCreated(function(){ 
    // counter starts at 0 
    this.counter = new ReactiveVar(0); 
}); 

它工作正常。

因此,我没有收到关于this关键字的ES6胖箭头绑定的问题。

当流星调用onCreated处理函数时,它将函数的this值绑定到模板实例。 Arrow functions词汇绑定this,这意味着在箭头函数内的this是相同的功能定义,在您的情况下可能window。因此,您正在创建一个全局变量counter,而不是将其分配给模板实例。

对于onCreated,onRendered等,使用箭头函数是没有意义的。

+0

有趣。我认为箭头函数是所有*函数需要写入ES6的方式吗?这是否意味着在ES6中,您实际上需要考虑使用哪种类型的函数,尤其是在使用'this'时? BTW'计数器'确实是作为一个全局变量创建的。 – fuzzybabybunny

+0

确切地说,这两种功能都有自己的用例。有时,你选择哪一个并不重要,但是'this'上下文由框架提供的回调(如'onCreated')是一个需要“正常”功能的例子。这里有一篇很好的文章,列出了其他一些案例:https://rainsoft.io/when-not-to-use-arrow-functions-in-javascript/。在我的项目中,我总是使用'函数',除非箭头函数使代码更易于阅读。 – chrisklaussner

+1

Ohhhhhh ....谢谢。超级有价值的信息。 – fuzzybabybunny