问题
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();
}
How can I pass this.userId inside a function? Does a function has to be binded with Meteor.bindEnvironment?
回答1:
You have some variants to resolve this:
use
.bind()
method:myMethod: function () { console.log(this.userId); // this returns proper userId function innerFunction() { console.log(this.userId); // this returns undefined } innerFunction.bind(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); }
also you can just use
that
insted ofthis
for pass the scope into ininnerFunction
:myMethod: function () { var that = this; console.log(this.userId); // this returns proper userId function innerFunction() { console.log(that.userId); // this returns undefined } innerFunction(); }
or just pass userId into
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(); }
回答2:
There are a couple of ways you can do it:
myMethod: function () {
var me = this;
function innerFunction () {
console.log(me.userId);
};
innerFunction();
}
or
myMethod: function () {
var innerFunction = function () {
console.log(this.userId);
}.bind(this);
innerFunction();
}
回答3:
have you tried to bind the function ?
myMethod: function(){
console.log(this.userId); // this returns proper userId
function innerFunction(){
console.log(this.userId); // this returns undefined
}.bind(this);
innerFunction();
}
来源:https://stackoverflow.com/questions/30576136/how-to-get-this-userid-in-function-inside-meteor-method