[英]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.