【问题标题】:Pass in jQuery/plainJS variables/functions of a current scope to anonymous function called from current scope将当前作用域的 jQuery/plainJS 变量/函数传递给从当前作用域调用的匿名函数
【发布时间】:2010-11-13 08:00:07
【问题描述】:

如何将当前作用域变量和函数传递给纯 Javascript 或 jQuery 中的匿名函数(如果它是特定于框架的)。

例如:

jQuery.extend({
  someFunction: function(onSomeEvent) {
    var variable = 'some text'
    onSomeEvent.apply(this); // how to pass current scope variables/functions to this function?
    return null;

    _someMethod(arg) {
      console.log(arg);
    }
  }
});

应该从上面的函数中登录firebug:

jQuery.someFunction(function(){
  console.log(this.variable); // or console.log(variable);
  console.log(this._someMethod(1); // or jQuery.someFunction._someMethod(2);
});

谢谢!

【问题讨论】:

    标签: javascript jquery scope


    【解决方案1】:

    阅读 JavaScript 中的作用域,例如“Java Script:好的部分”。

    在 Java 脚本中,函数内部只有作用域。 如果您使用 var 在函数内部指定变量,则无法从该函数外部访问它们。这是在 JavaScript 中创建私有变量的方法。

    您可以使用 this 变量,它指向您所在的当前对象(这不是范围本身)。但!如果您在没有 new 命令的情况下启动函数,则 this 将指向外部范围(在大多数情况下,它是窗口对象 = 全局范围)。

    例子:

    function foo(){
      var a = 10;
    }
    var f = foo(); //there is nothing in f
    var f = new foo(); //there is nothing in f
    
    function bar(){
      this.a = 10;
    }
    var b = new bar(); //b.a == 10
    var b = bar(); //b.a == undefined, but a in global scope
    

    顺便说一句,请查看 apply 方法 Mozilla docs/apply 的语法 所以你可以看到,第一个参数是对象,当你的方法被调用时,它将是 this

    所以考虑这个例子:

    function bar(){ 
      console.log(this.a);
      console.log(this.innerMethod(10)); 
    }
    
    function foo(){ 
      this.a = 10;
      this.innerMethod = function(a){
         return a+10;
      }
    
      bar.apply(this); 
    }
    
    var f = new foo(); // => you will get 10 and 20 in the console.
    var f = foo(); // => you will still get 10 and 20 in the console. But in this case, your "this" variable //will be just a global object (window)
    

    也许做起来更好

    var that = this;
    

    在调用 apply 方法之前,但可能不需要。不确定

    所以,这肯定会奏效:

    function foo(){
      console.log(this.a);
    }
    jQuery.extend({
     somefunc: function(func){
       this.a = 10;
       func.apply(this);
     }
    });
    
    $.somefunc(foo); //will print 10.
    

    【讨论】:

      【解决方案2】:

      第 1 行之前:

      var that = this;
      

      然后更改第 4 行:

      onSomeEvent.apply(that);
      

      【讨论】:

      • 以及如何调用函数和变量?使用 this.variable?
      • 简化:(function(){var _this = this;var a = 2;console.log(_this.a);})(); - 如何从另一个变量中获取一个变量,散列或者我不知道还有什么...
      猜你喜欢
      • 2013-09-23
      • 2017-08-13
      • 2018-04-17
      • 2019-01-24
      • 1970-01-01
      • 2011-03-11
      • 2011-11-30
      • 2017-05-27
      • 2011-02-17
      相关资源
      最近更新 更多