代码之家  ›  专栏  ›  技术社区  ›  kevzettler

在javascript中,这个范围是可能的吗?

  •  2
  • kevzettler  · 技术社区  · 16 年前

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

    我要做的是在作用域链上进一步声明变量,这样就可以在模块中访问这些变量,而不必像第二个示例那样使用这个关键字。我不认为这是可能的,因为函数的声明中似乎密封了函数的执行范围。

    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();
        }
      };
    };
    
    3 回复  |  直到 13 年前
        1
  •  2
  •   Greck    13 年前

    你要找的叫做 dynamic scoping “,其中通过搜索当前调用链来解析绑定。它在Lisp家族之外并不常见(Perl通过 local 关键字)。JS中不支持动态作用域,它使用 lexical scoping .

        2
  •  2
  •   Russ Cam    16 年前

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

    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 在执行时,这将按预期工作。

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

        3
  •  -1
  •   Tobias Cohen    16 年前

    放 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);
        }
      };
    };
    
    推荐文章