我想动态创建一个闭包。请参阅以下代码以获取解释。
function myFunction(){
parentScopedVar(); //Would like to be able to call without using 'this'.
}
function myDynamicFunc(dynamicClosure){
//What do I need to do here to dynamically create
//a var called 'parentScopedVar' that can be referenced from myFunction?
myFunction.call(self);
}
myDynamicFunc(
{
parentScopedVar : function() { alert('Hello World'); }
});
答案 0 :(得分:1)
Javascript使用lexical scope(基于声明代码的位置),而不是动态范围。
如果您决定尝试做一些语言并不真正鼓励的事情,您可以使用eval(string of code here)
强制在当前执行上下文中评估一串代码。事实上,你可以使用eval()
做各种奇怪的事情,但我更倾向于以一种利用Javascript优势的方式编写代码,而不是使用违背主要设计主题的编码风格。语言(我的意见)。
我并不完全清楚你要解决的问题是什么,但你可以将函数作为参数传递,然后通过被调用函数中的参数调用它。
// declare your function that takes a function reference an argument
function myFunction(callback) {
// call the function that was passed
callback();
}
function myDynamicFunc(){
// declare a local function
function myAlert() {
alert('Hello World');
}
// call your other function and pass it any function reference
myFunction(myAlert);
}
这不会传递整个执行上下文。为此,您必须在对象中打包上下文并传递对象的引用,然后从对象中取消引用属性。这通常是您在JS中传递环境的方式。
您可以使用本地声明的函数来提供对回调(同样是词法范围)的父作用域的访问:
// declare your function that takes a function reference an argument
function doSomething(callback) {
// call the function that was passed
callback();
}
function myFunc() {
var myLocal1 = "Hello";
var myLocal2 = "World";
function callback() {
// when this is called, it has access to the variables of the parent scope
alert(myLocal1 + " " + myLocal2);
}
doSomething(myFunc);
}
您甚至可以将其用作持久封闭:
// declare your function that takes a function reference an argument
function doSomething(callback) {
// call the function that was passed
callback();
}
function myFunc() {
var myLocal1 = "Hello";
var myLocal2 = "World";
function callback() {
// when this is called, it has access to the variables of the parent scope
// which are still alive in this closure even though myFunc has finished
// executing 10 minutes ago
alert(myLocal1 + " " + myLocal2);
}
// call the callback function 10 minutes from now,
// long after myFunc has finished executing
setTimeout(callback, 10 * 60 * 1000);
}
以下是Javascript中词汇和动态范围的一些参考文章:
Is it possible to achieve dynamic scoping in JavaScript without resorting to eval?
Are variables statically or dynamically "scoped" in javascript?