如何在Meteor方法中的函数中获取this.userId [英] How to get this.userId in function inside Meteor method
问题描述
我需要为每个登录的用户多次调用一个函数,但是当将该函数放置在流星方法内部时,this.userId在函数范围内变为未定义,这是示例:
I need to call a few times a function for every user who is logged in, but when the function is placed inside meteor method, this.userId becomes undefined inside function scope, here's the example:
myMethod: function(){
console.log(this.userId); // this returns proper userId
function innerFunction(){
console.log(this.userId); // this returns undefined
};
innerFunction();
}
如何在函数内传递this.userId? 功能是否必须与Meteor.bindEnvironment绑定?
How can I pass this.userId inside a function? Does a function has to be binded with Meteor.bindEnvironment?
推荐答案
您可以使用一些变体来解决此问题:
You have some variants to resolve this:
-
使用
.bind()
方法:
myMethod: function () {
console.log(this.userId); // this returns proper userId
function innerFunction() {
console.log(this.userId); // this returns undefined
}
innerFunction.bind(this);
}
使用.apply()
方法将正确的this
应用于函数:
use .apply()
method for applying correctthis
into function:
myMethod: function () {
console.log(this.userId); // this returns proper userId
function innerFunction() {
console.log(this.userId); // this returns undefined
};
innerFunction.apply(this);
}
,您也可以只使用this
的that
来将范围传递到innerFunction
中:
also you can just use that
insted of this
for pass the scope into in innerFunction
:
myMethod: function () {
var that = this;
console.log(this.userId); // this returns proper userId
function innerFunction() {
console.log(that.userId); // this returns undefined
}
innerFunction();
}
或仅将userId传递到innerFunction
myMethod: function () {
var userId = this.userId;
console.log(this.userId); // this returns proper userId
function innerFunction(userId) {
console.log(userId); // this returns undefined
}
innerFunction();
}
这篇关于如何在Meteor方法中的函数中获取this.userId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!