繁体   English   中英

Javascript:运行在此闭包外部定义的函数,就像在该闭包内部定义的一样

[英]Javascript: Run a function defined outside this closure as if it were defined inside this closure

我想要一个函数A,它接受另一个函数B作为参数,然后运行它在A的闭包范围内定义的B,即可以访问所有局部变量。

例如,简单地说:

var A = function(B){
  var localC = "hi";
  B();
}

var B = function(){
  console.log(localC);
}

A(B); // to log 'hi'

我发现的唯一方法是使用eval。 ec6可能会提供更好的选择吗?

一种解决方案是将localC作为参数传递localC函数B

 var A = function(B) { var localC = "hi"; B(localC); } var B = function(localC) { console.log(localC); } A(B); // outputs hi 

使用arguments替代方法:

 var A = function(B) { var localC = "hi"; B(localC, "test"); } var B = function() { var i = 0; for (i; i < arguments.length; i++) { console.log(arguments[i]); } } A(B); // outputs hi, test 

 var A = function(B){ var self = this; self.localC = "hi"; self.localD = "hello"; B(); }; var B = function(){ var self=this; alert(self.localD); } A(B); // to log 'hi' 

您可以使上下文显式并将其传递给B

var A = function(B){
    var context = {
        localC: "hi"
    };
    B(context);
}

var B = function(context){
    console.log(context.localC);
}

A(B); // hi

您还可以将thisnewprototype

var A = function() {
    this.localC = "hi";
}
A.prototype.b = function(context){
    console.log(this.localC);
}

var a = new A();
a.b(); // hi

还是没有prototype

var A = function() {
    this.localC = "hi";
}

var a = new A();
a.b = function(context){
    console.log(this.localC);
};
a.b(); // hi

您可以将thisbind一起使用:

var a = {
    localC: "hi"
};
function B(foo) {
    console.log(this.localC, foo);
}
B.bind(a)("foo"); // hi foo
// .call:
B.call(a, "foo"); // hi foo

bind this设置上下文。 call将上下文作为第一个参数。


这个人是不是好:

var A = function(B){
    var localC = "hi";
    B.bind(this)(); // this is the global object, you need `new` to create a new scope
}

var B = function(){
    console.log(this.localC);
}
A(B); // undefined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM