您也可以使用這樣的模式:
var obj = (function() {
var methods = {
creator: function(ch) {
},
fieldsCreators:{
INVITER: function() {
return methods.creator('a');
},
CUSTOMER: function() {
return methods.creator('b');
}
}
};
return methods;
})();
這有什麼用?假設你想讓所有的方法訪問一個變量,但只能在obj中看到。如果obj只是一個對象,你就無法做到這一點,它需要一個函數的範圍。例如:
var obj = (function() {
// everything declared with var won't be visible to the rest
// of the application, which is good encapsulation practice.
// You only return what you want to be publicly exposed.
var MYPRIVATEINFO = "cheese";
var methods = {
creator: function(ch) {
// you have access to MYPRIVATEINFO here
// but the rest of the application doesn't
// even know about it.
},
fieldsCreators:{
INVITER: function() {
return methods.creator('a');
},
CUSTOMER: function() {
return methods.creator('b');
}
}
};
return methods;
})();
如果你不希望有命名對象,可以構建像這樣,這就是爲什麼有一個私密的環境是關鍵:
var obj = (function() {
var creator = function(ch) {
};
return {
// if you wish, you can still expose the creator method to the public:
creator: creator,
fieldsCreators: {
INVITER: function() {
return creator('a');
},
CUSTOMER: function() {
return creator('b');
}
}
};
})();
來源
2011-05-19 15:15:32
Eli
爲什麼你的例子是Amir Raminfar解決方案的更好解決方案? – 2011-05-19 15:18:58
它允許你有一個私人的環境。我將更新關於如何做到這一點的帖子。 – Eli 2011-05-19 15:19:57
除了Eli說你可以選擇哪些方法是私人的和公開的,它的確是一樣的。但是再次使用'方法'就像使用'obj' – 2011-05-19 15:23:55