为什么模块模式要创建单例?

2024-04-10

当我尝试创建该模块的不同实例时,它不起作用。

看来是单例了。我一次只能有一个实例。

什么机制限制构造函数 publik() 只能在实例上使用?

http://jsfiddle.net/AVxZR/ http://jsfiddle.net/AVxZR/

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();

模块模式并不意味着以您所描述的方式使用。它用于创建一个模块并对外部代码隐藏状态,即公开一个公共接口,外部代码可以与该接口进行通信,但将其余部分隐藏。

这可以防止其他代码依赖您在内部使用的变量或函数,因为当您重命名任何内容时它们会中断。

另外,模块应该是单例的;拥有多个相同的模块就像在代码中拥有两个相同的类......没有意义。

这就是模块模式应有的样子。

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()已公开,但没有其他私有变量/函数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么模块模式要创建单例? 的相关文章