单例实例范围混淆JavaScript

时间:2016-01-20 12:04:49

标签: javascript design-patterns singleton

我正在学习JavaScript中的设计模式,我正在经历Singleton设计模式。这是代码:

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

我不明白为什么变量instancesingletonTest1启动时会获得一些价值。

1 个答案:

答案 0 :(得分:1)

创建模块SingletonTester时,也会调用它:

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

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

由于instance是由SingletonTester闭包关闭的属性,因此实例 alive 表示整个SingletonTester存在。

附注: Singleton模式主要用于创建一个线程安全的静态实例,以便跨进程共享。由于JavaScript是单线程的,因此这显然不是问题。您可以改为简单,只需使用全局变量。