我正在研究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();
}
};
};
第一個例子中定義了wot? – 2010-01-30 22:44:32
@musicfreak:OP說他得到'wot'未定義的錯誤。如果你沒有在任何地方用'var'關鍵字定義一個變量,那麼JS會把它作爲'window'對象的一個屬性來查找。 – 2010-01-30 22:48:40
@Tobias:我明白這一點。我想知道OP要訪問的對象位於何處 - 換句話說,他在尋找什麼範圍。 – 2010-01-31 07:04:25