从单实例和多实例的 Angular 来看,为什么我要按照模块模式编写所有这些额外的代码行,而不是只使用标准构造函数,方法和属性在构造函数主体中定义?
模块模式示例:http://jsfiddle.net/T3ZJE/1/
var module = (function () {
// private variables and functions
var foo = 'bar';
// constructor
var module = function () {
};
// prototype
module.prototype = {
constructor: module,
something: function () {
}
};
// return module
return module;
})();
var my_module = new module();
console.log(my_module)
构造函数示例:http://jsfiddle.net/EuvaS/2/
function Module(){
// private variables and functions
var foo = 'bar';
//public methods
this.something = function () {
}
}
var my_module = new Module();
console.log(my_module);
对我来说,最终结果几乎是一样的。两者都可以有公共(public)属性和方法,都可以有可以被公共(public)方法访问的“私有(private)”变量和方法。
两者都将为单例定义一次公共(public)/原型(prototype)方法,都将为对象的多个实例/克隆定义多次。
我错过了什么吗?有什么区别?
最佳答案
在第一个示例中,foo 将是所有 module() 实例共有的静态变量。这意味着,所有实例都将引用相同的变量。
在第二个例子中,每个 Module() 实例的 foo 都是不同的。
除此之外,我看不出有任何区别。
关于JavaScript 模块模式与构造函数中定义的方法的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13611752/