[英]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
您還可以將this
與new
和prototype
:
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
您可以將this
與bind
一起使用:
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.