2010-01-30 30 views
2

我正在研究JavaScript框架。我有幾個獨立的腳本,如下所示:這是可能在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(); 
    } 
    }; 
}; 
+0

第一個例子中定義了wot? – 2010-01-30 22:44:32

+0

@musicfreak:OP說他得到'wot'未定義的錯誤。如果你沒有在任何地方用'var'關鍵字定義一個變量,那麼JS會把它作爲'window'對象的一個​​屬性來查找。 – 2010-01-30 22:48:40

+0

@Tobias:我明白這一點。我想知道OP要訪問的對象位於何處 - 換句話說,他在尋找什麼範圍。 – 2010-01-31 07:04:25

回答

2

您要查找的內容稱爲「dynamic scoping」,其中綁定通過搜索當前的調用鏈來解決。它在Lisp系列之外並不常見(Perl支持它,通過關鍵字local)。 JS中不支持動態範圍,它使用lexical scoping

-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); 
    } 
    }; 
}; 
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,此無線將按預期工作。

稍微偏離主題,但您已經觸及了功能的範圍。函數具有詞法範圍,即它們在它們被定義的位置創建它們的範圍(而不是執行)並允許創建閉包;當一個函數保留一個到它的父作用域的鏈接時,即使在父對象返回後,也會創建一個閉包。