2

我正在开发一个 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();
    }
  };
};
4

3 回答 3

2

考虑这个例子,使用你的代码

var core = {}; // define an object literal
core.modules = {}; // define modules property as an object

var wot= 'Muhahaha!';

core.modules.example_module = function(sandbox){

  console.log('wot from creator ==', wot);

  return {
    init: function() {
       console.log('wot from init ==', wot);

    }
  }
}

// logs wot from creator == Muhahaha! to the console    
var anObject = core.modules.example_module(); 

// logs wot from init == Muhahaha! to the console
anObject.init(); 

只要wot在作用域链中的某个地方定义了core.modules.example_module它的执行点,它就会按预期工作。

稍微偏离主题,但您已经触及了函数的范围。函数具有词法作用域,即它们在定义它们的点(而不是执行)创建它们的作用域,并允许创建闭包;当一个函数保持到它的父作用域的链接时,即使在父作用域返回之后,也会创建一个闭包。

于 2010-01-30T23:05:49.760 回答
2

您正在寻找的内容称为“动态范围”,其中绑定是通过搜索当前调用链来解决的。它在 Lisp 家族之外并不常见(Perl 支持它,通过local关键字)。使用词法作用域的 JS 不支持动态作用域。

于 2010-02-01T00:38:02.127 回答
-1

放在var wot;构造函数的开头应该这样做

core.modules.example_module = function(sandbox){
  var wot;
  wot = 'foo'; //just so you can see it working
  console.log('wot from constructor ==', wot);

  return{
    init : function(){
      console.log('wot from init ==', wot);
    }
  };
};
于 2010-01-30T22:42:09.440 回答