執行doOtherStuff()
這個代碼是什麼,簡單地說:創建並運行的功能,並指定其返回值的變量:Module
。返回值是具有1個屬性的對象:public_instance_var
,指向變量instance_var
,或(在更正錯字後:public_instance_var
)。這個變量被聲明瞭,但沒有實例化。因此,返回值是這樣的:
Module.public_instance_var = undefined
最後一行Module.doStuff();
行不通一位:模塊是一個沒有方法的對象。您聲明的函數在匿名函數返回時收集垃圾。如果你想訪問這些函數,你需要將它們包含在return語句中。閱讀上封鎖,對象構造和設計模式一般,但我會說你後的代碼會是這個樣子:
var Module = (function()
var public_instance_var;
function doStuff() {
this.doOtherStuff();
console.log(public_instance_var); // expected: true, but logs undefined
};
function doOtherStuff() {
public_instance_var = true;
};
return {
public_instance_var: public_instance_var,
doStuff: doStuff,
doOtherStuff: doOtherStuff
};
})();
當然,這樣一來你的變量public_instance_var
是公共財產,所以我的猜測是你真正想要做的是模擬一個私有屬性和方法。在這種情況下,你可能最終得到類似下面的代碼:
var Module = (function()
{
var public_instance_var;
return {
//public_instance_var: public_instance_var, remove this line
//the closure will preserve access to the variable
doStuff: function()
{
this.doOtherStuff();//this, you're referencing the object's property
console.log('here I am');
},
doOtherStuff: function()
{
public_instance_var = true;
//this won't work anymore:
//this.public_instance_var = true;
};
}
})();
Module.doStuff()
現在記錄here I am
,但現在doOtherStuff
是一個公共的方法,太。這裏是你會如何選擇解決問題:
var Module = (function()
{
var public_instance_var;
function doOtherStuff()
{
public_instance_var = true;
};
return {
//public_instance_var: public_instance_var, remove this line
//the closure will preserve access to the variable
doStuff: function()
{
doOtherStuff();//don't use this here, but the reference to the function exists thanks to closure
console.log('here I am');
console.log(public_instance_var);//logs true
}
};
})();
這些只是少數人的非常強大的東西,你可以封鎖和返回對象的功能做。
只要閱讀幾篇文章,如this之一,那裏有更好的文章。谷歌術語power constructors
看起來像你錯過了instance_var – Madman 2012-07-31 11:42:23
在返回中是否有錯字? instance_var在哪裏定義? – ThirdOne 2012-07-31 11:42:55
'Module.doStuff();'應該拋出'Module'沒有可調用屬性'doStuff'(或類似的)的錯誤。與您的評論的行永遠不會執行。另外,這與OOP沒有任何關係。 – 2012-07-31 11:44:12