当我尝试创建此模块的不同实例时,它不起作用。
好像是单例。我一次只能有一个实例。
什么机制限制构造函数 publik() 只能有实例?
var Module = ( function ()
{
var publik = function ( )
{
};
publik.prototype.test;
publik.prototype.get = function()
{
document.getElementById( 'a'+test ).innerHTML = test;
};
publik.prototype.set = function( value )
{
test = value;
};
return publik;
} ) ();
var object1 = new Module();
var object2 = new Module();
object1.set('1');
object2.set('2');
object1.get();
object2.get();
最佳答案
模块模式并不意味着以您描述的方式使用。它用于创建一个模块并对外部代码隐藏状态,即您公开一个公共(public)接口(interface),外部代码可以与之通信,但您将其余部分隐藏起来。
这可以防止其他代码依赖于您在内部使用的变量或函数,因为它们会在您重命名任何内容时中断。
此外,模块应该是单例的;有多个相同的模块就像在你的代码中有两个相同的类......没有意义。
这就是模块模式的样子。
var Module = (function($) {
// the $ symbol is an imported alias
// private variable
var id = 0;
// private function
function increaseId()
{
return ++id;
}
// return public interface
return {
nextId: function() {
// we have access to the private function here
// as well as the private variable (btw)
return increaseId();
}
}
}(jQuery)); // we import jQuery as a global symbol
Module.nextId(); // 1
Module.nextId(); // 2
Module.id; // undefined
Module.increaseId(); // error
您会看到如何只公开了 .nextId()
,而没有公开其他私有(private)变量/函数。
关于javascript - 为什么模块模式会创建单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10691300/