为什么模块模式会创建一个单例? [英] Why does module pattern create a singleton?

查看:76
本文介绍了为什么模块模式会创建一个单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试制作这个模块的不同实例时,它不起作用。

When I try and make different instances of this module, it does not work.

它似乎是一个单身人士。我一次只能有一个实例。

It seems to be a singleton. I can only have one instance at a time.

什么机制限制构造函数publik()只有实例?

What mechanism limits the constructor function publik() to only have on instance?

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


推荐答案

简答:关闭。

答案很长(如果我说得对,请发表评论以便我更正):

The long answer (if I have it right, please comment so I can correct):


  1. 您的模块var在脚本加载时立即执行。 (由函数周围的括号表示。)()

  1. Your Module var is a executed immediately when the script loads. (denoted by the parenthesis around the function.)()

在该模块中,您的publik var被声明,并且即使在封闭时它仍然是函数完成!

In that module, your publik var is declared and it's left in the closure even when the function completes!

通过后续调用,您仍然可以访问自动执行的那个模块。总之,它总是得到相同的闭包空间和函数范围以及相同的对象 - 所以你的publik变量实际上总是相同的。

With subsequent calls, you still access that one Module that was auto-executed. And it always gets that same closure space and function scope and the same object, in short - so your publik variable is actually always the same one.

这篇关于为什么模块模式会创建一个单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆