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

Javascript 如何在Meteor方法内的函数中获取this.userId,javascript,methods,meteor,Javascript,Methods,Meteor,我需要为每个登录的用户调用函数几次,但是当函数放在meteor方法中时,this.userId在函数范围内变得未定义,以下是示例: myMethod: function(){ console.log(this.userId); // this returns proper userId function innerFunction(){ console.log(this.userId); // this returns undefined }; innerFuncti

我需要为每个登录的用户调用函数几次,但是当函数放在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();
}


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

  • 使用
    .bind()
    方法:

    myMethod: function () {
     console.log(this.userId); // this returns proper userId
    
     function innerFunction() {
         console.log(this.userId); // this returns undefined
     }
    
     innerFunction.bind(this);
    }
    
  • 使用
    .apply()
    方法将正确的
    应用到函数中:

    myMethod: function () {
     console.log(this.userId); // this returns proper userId
    
     function innerFunction() {
         console.log(this.userId); // this returns undefined
     };
    
     innerFunction.apply(this);
    }
    
  • 您也可以使用
    that
    代替
    this
    将作用域传递到
    内部函数中:

    myMethod: function () {
        var that = this;
        console.log(this.userId); // this returns proper userId
    
        function innerFunction() {
           console.log(that.userId); // this returns undefined
        }
    
        innerFunction();
    }
    
  • 或者只需将用户ID传递到
    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.userId()
编写?谢谢,我想避免将userId添加为函数参数,但其他解决方案正是我想要的,尤其是语法最简单的.bind(此)解决方案。@DariuszSikorski我很高兴我的解决方案能帮助您:)a.bind()解决方案返回错误或意外标记。这与{…}之后的这个点有关,但是由于每个人都提到这个解决方案,它可能是一种局部问题,但是我检查了innerFunction.apply(这个);而且工作没有问题。@DariuszSikorski啊。。没错。我对
.bind()
的答案进行了更改,更改后的.apply to.bind函数根本没有启动,但不会引发任何错误,服务器正在启动,事实上现在。bind和.apply解决方案看起来非常接近,所以我会坚持使用。apply解决方案,再次感谢:)此代码无法工作,因为
.bind()
应该像
innerFunction.bind(this)
myMethod: function () {
  var userId = this.userId;
  console.log(this.userId); // this returns proper userId

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

  innerFunction();
}