ES6箭头功能正在改变Meteor.publish中的范围 [英] ES6 Arrow function is changing the scope of this in Meteor.publish
问题描述
所以我开始在 Meteor
中使用ES6,但显然如果你尝试使用 Meteor.publish
语法一个箭头函数 this.userId
是未定义的,而如果您使用常规的函数(){}
this.userId
完美地工作,Im假设是一种透明过程,它将不同的指派给 userId
,但只是一个猜测,有没有人知道真正发生了什么?
So I been started using ES6 in Meteor
, but apparently if you try to use Meteor.publish
syntax with an arrow function, this.userId
is undefined, while if you use it with a regular function(){}
this.userId
works perfectly, Im assuming is a kind of transpiler process that assign a different this, to userId
but is just a guess, does anyone knows what really is happening?
Meteor.startup(function() {
Meteor.publish("Activities", function() { //with function
console.log(this.userId); //TS8vTE3z56LLcaCb5
});
});
Meteor.startup(function() {
Meteor.publish("Activities", ()=> { //with arrow function
console.log(this.userId); //undefined
});
});
推荐答案
这不是一个透视错误,箭头功能的href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this功能。箭头函数自动将函数体的上下文设置为此处创建的上下文,在这种情况下,回调到 Meteor.publish
。这样可以防止Meteor重新绑定您的监听器功能的上下文。
This isn't a transpilation error, it's a feature of arrow functions. The arrow function automatically sets the context of the function body to the contexts here it was created, in this case the callback to Meteor.publish
. This prevents Meteor from rebinding the context of your listener function.
从Meteor 发布文档:
在函数内部,这是发布处理程序对象
Inside the function, this is the publish handler object
如果您希望事情正常工作,您将需要使用旧校功能语法来允许Meteor正确设置上下文。
If you want things to work properly you will need to use the "old-school" function syntax to allow Meteor to set the context properly.
这篇关于ES6箭头功能正在改变Meteor.publish中的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!