Javascript 将当前作用域的jQuery/plainJS变量/函数传递给从当前作用域调用的匿名函数

Javascript 将当前作用域的jQuery/plainJS变量/函数传递给从当前作用域调用的匿名函数,javascript,jquery,scope,Javascript,Jquery,Scope,如何将当前范围变量和函数传递给普通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 nu

如何将当前范围变量和函数传递给普通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);
});
谢谢

在第1行之前:

var that = this;
然后更改第4行:

onSomeEvent.apply(that);

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

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

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

例如:

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方法的语法 您可以看到,第一个参数是object,当调用您的方法时,它将是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.

如何调用函数和变量?使用this.variable?简化:(function(){var\u this=this;var a=2;console.log(_this.a);})();-如何从另一个变量获取变量,哈希或我不知道还有什么。。。