[英]What is the best way to deal with this Namespace JavaScript Structure?
[英]Best way to define obj constructor in namespace javascript
我想將obj構造函數保留在某些命名空間中,而在調試時沒有問題。
現在我有這樣的代碼:
var namespace = {};
namespace.myConstructor = function(){};
// ----------- debug in console
(new namespace.myConstructor()); // -> namespace.myConstructor {}
(new namespace.myConstructor()).constructor; // -> function (){}
我不喜歡那個構造函數是匿名的。 所以我可以用其他方式做到這一點:
(更好,但是很丑)
var namespace = {};
namespace.myConstructor = (function(){
function myConstructor(){};
return myConstructor;
})();
// ----------- debug in console
(new namespace.myConstructor()); // -> myConstructor {}
(new namespace.myConstructor()).constructor; // -> function myConstructor(){}
或(最美麗,最短的方法)
namespace.myConstructor = function myConstructor(){};
// ----------- debug in console
(new namespace.myConstructor()); // -> myConstructor {}
(new namespace.myConstructor()).constructor; // -> function myConstructor(){}
但是我在這里讀到NFE(命名函數表達式)存在一些問題。
哪種方法更好? 哪種方法是好的做法?
IE8問題被誇大了,在實踐中根本沒有任何關系,因為這些函數將在短暫的IIFE中聲明,而這些IIFE仍然無法按名稱引用該函數,因為這樣您的代碼將無法在實際的瀏覽器中運行。
記住要大寫構造函數名稱。
(function(){
var namespace = {
MyConstructor: function MyConstructor() {
},
...
}
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.