如何在 Meteor 方法中的函数中获取 this.userId

How to get this.userId in function inside Meteor method

我需要为每个登录的用户调用几次函数,但是当函数放在 meteor 方法中时,this.userId 在函数范围内变为未定义,这里是示例:

myMethod: function(){

  console.log(this.userId); // this returns proper userId

  function innerFunction(){
    console.log(this.userId); // this returns undefined
  };
  innerFunction();

}

如何在函数内部传递 this.userId? 函数是否必须与 Meteor.bindEnvironment 绑定?

你试过绑定函数吗?

   myMethod: function(){

      console.log(this.userId); // this returns proper userId


  function innerFunction(){
    console.log(this.userId); // this returns undefined
  }.bind(this);
  innerFunction();

}

有几种方法可以做到:

myMethod: function () {
    var me = this;

    function innerFunction () {
        console.log(me.userId);
    };

    innerFunction();
}

myMethod: function () {
    var innerFunction = function () {
        console.log(this.userId);
    }.bind(this);

    innerFunction();
}

您有一些变体可以解决此问题:

  • 使用.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 应用到函数中:

    myMethod: function () {
     console.log(this.userId); // this returns proper userId
    
     function innerFunction() {
         console.log(this.userId); // this returns undefined
     };
    
     innerFunction.apply(this);
    }
    
  • 您也可以使用 that 代替 this 将作用域传递到 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();
    }