【问题标题】:How to get this.userId in function inside Meteor method如何在 Meteor 方法中的函数中获取 this.userId
【发布时间】:2015-06-01 14:27:33
【问题描述】:

我需要为每个登录的用户调用几次函数,但是当该函数放在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 绑定?

【问题讨论】:

  • 你试过写成Meteor.userId()吗?

标签: javascript methods meteor


【解决方案1】:

你有一些变体来解决这个问题:

  • 使用.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 insted of 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();
    }
    

【讨论】:

  • 谢谢,我想避免将 userId 添加为函数参数,但其他解决方案正是我想要的,尤其是语法最简单的 .bind(this) 解决方案。
  • @DariuszSikorski 我真的很高兴我的解决方案能帮到你:)
  • A .bind() 解决方案返回错误意外令牌。这与 { ... } 之后的这个点有关,但是由于每个人都提到了这个解决方案,它可能是一种局部问题,但我检查了 innerFunction.apply(this);并且没有问题。
  • @DariuszSikorski aah.. 是的。我已经更改了.bind() 的答案
  • 从 .apply 更改为 .bind 函数根本没有启动,但不会抛出任何错误并且服务器正在启动,实际上现在 .bind 和 .apply 解决方案看起来非常接近,所以我会坚持使用 .apply 解决方案,再次感谢 :)
【解决方案2】:

有几种方法可以做到:

myMethod: function () {
    var me = this;

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

    innerFunction();
}

或

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

    innerFunction();
}

【讨论】:

    【解决方案3】:

    你试过绑定函数吗?

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

    【讨论】:

    • 这段代码不能工作,因为.bind()应该像innerFunction.bind(this)一样执行
    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2016-06-15
    • 1970-01-01
    • 2010-09-19
    • 2020-01-26
    相关资源
    最近更新 更多