我正在开发一个 javascript 框架。我有几个看起来像这样的独立脚本:
core.modules.example_module = function(sandbox){
console.log('wot from constructor ==', wot);
return{
init : function(){
console.log('wot from init ==', wot);
}
};
};
这个函数是从另一个外部脚本调用的。我正在尝试将变量传递给此函数,以便可以访问它们without using the this keyword.
上面的例子会出错,说 wot 是未定义的。
如果我将函数包装在一个匿名函数中并在那里声明变量,我会得到预期的结果
(function(){
var wot = 'omg';
core.modules.example_module = function(sandbox){
console.log('wot from creator ==', wot);
return{
init : function(){
console.log('wot from init ==', wot);
}
};
};
})();
我要做的是在作用域链的上游声明变量,以便可以在模块中访问它们,而无需像第二个示例那样使用 this 关键字。我不相信这是可能的,因为看起来函数执行范围在函数声明时是密封的。
update
为了澄清我试图定义 wot 的位置。在一个单独的 javascript 文件中,我有一个像这样调用注册模块函数的对象
core = function(){
var module_data = Array();
return{
registerModule(){
var wot = "this is the wot value";
module_data['example_module'] = core.modules.example_module();
}
};
};