ES6 箭头函数正在改变 Meteor.publish 中 this 的范围 [英] ES6 Arrow function is changing the scope of this in Meteor.publish

查看:17
本文介绍了ES6 箭头函数正在改变 Meteor.publish 中 this 的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我开始在 Meteor 中使用 ES6,但显然如果你尝试使用带有箭头函数的 Meteor.publish 语法,this.userId 未定义,而如果您将其与常规 function(){} this.userId 一起使用,则效果很好,我假设是一种分配不同这对 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
    });
});

推荐答案

这不是转译错误,而是 特性 箭头函数.箭头函数会自动将函数体的上下文设置为它在此处创建的上下文,在本例中是对 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 发布文档:

From the Meteor publish docs:

在函数内部,这是发布处理程序对象

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 中 this 的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆