我正在一个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未定义。

如果i将功能在一个匿名函数和声明变量有我得到预期的所需的结果

(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);
    }
  };
};

})();

我所要做的是进一步声明变量向上范围链,这样他们可以在模块中不使用该参数,如第二个例子进行访问。我不相信这是可能的,因为它看起来像功能的执行范围上的函数的声明密封。

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();
    }
  };
};
有帮助吗?

解决方案

您要寻找的被称为“动态作用域”,其中绑定解决通过搜索当前呼叫链。这不是Lisp的家庭太常见外(Perl的支持的话,通过local关键字)。动态作用域不JS,它使用词法作用域

支持

其他提示

考虑本示例中,使用代码

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范围链某处,这将正常工作。

稍微偏离主题,但你在功能范围感动。函数具有词法作用域的,即它们创建在它们被定义(而不是执行),并允许要创建封闭的点它们的范围;创建一个闭合时一个函数具有保持链接到父返回即使它的父范围。

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);
    }
  };
};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top