2016-01-20 59 views
0

我正在学习JavaScript中的设计模式,我正在通过Singleton设计模式。下面是代码:JavaScript中的单例实例范围混淆

var SingletonTester = (function() { 
    // options: an object containing configuration options for the singleton 
    // e.g var options = { name: 'test', pointX: 5}; 
    function Singleton(options) { 
     // set options to the options supplied or an empty object if none provided. 
     options = options || {}; 
     //set the name parameter 
     this.name = 'SingletonTester'; 
     //set the value of pointX 
     this.pointX = options.pointX || 6; 
     //set the value of pointY 
     this.pointY = options.pointY || 10; 
    } 
      // this is our instance holder 
    var instance; 

    // this is an emulation of static variables and methods 
    var _static = { 
     name: 'SingletonTester', 
     // This is a method for getting an instance 
     // It returns a singleton instance of a singleton object 
     getInstance: function (options) { 
      if (instance === undefined) { 
       instance = new Singleton(options); 
      } 
      return instance; 
     } 
    }; 
    return _static; 
})(); 
var singletonTest = SingletonTester.getInstance({ 
    pointX: 5 
}); 
var singletonTest1 = SingletonTester.getInstance({ 
    pointX: 15 
}); 
console.log(singletonTest.pointX); // outputs 5 
console.log(singletonTest1.pointX); // outputs 5 

我不明白为什么变量instance得到了一些值时启动singletonTest1

+0

在JS中,你不需要'Singleton',只需要使用一个全局变量。 –

+0

其次^,但如果你仍然想要一个单例模拟,那么谷歌为“JavaScript单身执行者”。有一些Git项目可以做到这一点。无论如何,不​​应该做出正确的判断。 JS是JS。 – Ingmars

+0

@DavinTryon这已经是单身模式,它工作正常。我的困惑是,当'singletonTest1'启动时''instance'变量有多值。至少在评论前阅读这个问题。 –

回答

1

在创建模块SingletonTester,它也被称为:

var SingletonTester = (function() { 
    // ... stuff in here 
    var instance; 
})(); // <--- here 

最后一行是功能应用();。在该应用程序之后,SingletonTester模块包含它所有的封闭状态。

由于instance是由SingletonTester关闭,例如关闭了一个属性是的SingletonTester整个存在活着

便笺:单例模式主要是为了创建一个线程安全的静态实例来跨进程共享。由于JavaScript是单线程的,这显然不是问题。您可以将事情简单化并使用全局变量。

+0

啊,现在我明白了,感到困惑。当然它是封闭的。非常感谢达文。 –