如何在Meteor方法中的函数中获取this.userId [英] How to get this.userId in function inside Meteor method

查看:85
本文介绍了如何在Meteor方法中的函数中获取this.userId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为每个登录的用户多次调用一个函数,但是当将该函数放置在流星方法内部时,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);
    }
    

  • ,您也可以只使用thisthat来将范围传递到innerFunction中:

  • also you can just use that insted of thisfor 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆