JavaScript 模块模式与构造函数中定义的方法的构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13611752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript module pattern vs Constructor with methods defined in constructor
提问by Fergal
From a single instance and a multiple instance point of view, why would I write all those extra lines of code following the Module Pattern vs just using a standard Constructor with methods and properties defined in the constructor body?
从单个实例和多个实例的角度来看,为什么我要按照模块模式编写所有这些额外的代码行,而不是仅使用标准构造函数以及在构造函数主体中定义的方法和属性?
Module Pattern sample : http://jsfiddle.net/T3ZJE/1/
模块模式示例: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)
Constructor sample : http://jsfiddle.net/EuvaS/2/
构造函数示例: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);
To me the end result is pretty much the same. Both can have public properties and methods, both can have "private" variables and methods which can be accessed by the public methods.
对我来说,最终结果几乎相同。两者都可以具有公共属性和方法,都可以具有公共方法可以访问的“私有”变量和方法。
Both will define public / prototype methods once for a singleton, both will define them multiple times for multiple instances / clones of the object.
两者都会为单例定义一次公共/原型方法,两者都会为对象的多个实例/克隆多次定义它们。
Am I missing something? What is the difference?
我错过了什么吗?有什么区别?
回答by Damp
In the first example, foo will be a static variable common to all instances of module(). Meaning, all instances will reference the same variable.
在第一个示例中, foo 将是 module() 的所有实例通用的静态变量。意思是,所有实例都将引用相同的变量。
In the second example, foo is different for each Module() instance.
在第二个示例中,每个 Module() 实例的 foo 都不同。
Apart from that, I don't see any difference.
除此之外,我看不出任何区别。
回答by David Lee
Nothing special difference. But I am not sure what is the point of the module pattern in this example. You don't need to include the constructor in the module. Constructors should be used like the second style. But it is better for the methods to be defined in its prototype object unless you need to have it for each instance.
没什么特别的区别。但我不确定这个例子中模块模式的重点是什么。您不需要在模块中包含构造函数。构造函数应该像第二种风格一样使用。但是最好在其原型对象中定义方法,除非您需要为每个实例都使用它。
Again in terms of purpose, I do not think that the module pattern here is proper way.
再次就目的而言,我不认为这里的模块模式是正确的方式。