简体   繁体   English

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

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

I want to have a function A that accepts another function B as an argument, and then runs B as it were defined within the closure scope of A, ie has access to all the local variables. 我想要一个函数A,它接受另一个函数B作为参数,然后运行它在A的闭包范围内定义的B,即可以访问所有局部变量。

For example, simplistically: 例如,简单地说:

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

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

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

The only way I have found is to use eval. 我发现的唯一方法是使用eval。 Does ec6 give any better options maybe? ec6可能会提供更好的选择吗?

One solution is to pass localC as argument in function B : 一种解决方案是将localC作为参数传递localC函数B

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

Alternative using arguments : 使用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' 

You can make the context explicit and pass it to B : 您可以使上下文显式并将其传递给B

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

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

A(B); // hi

You can also use this with new and prototype : 您还可以将thisnewprototype

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

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

or without the prototype : 还是没有prototype

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

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

You can use this with bind : 您可以将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 sets the context for this . bind this设置上下文。 call takes the context as it's first argument. call将上下文作为第一个参数。


This one is not good: 这个人是不是好:

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