JavaScript 中的单例实例范围混淆

Singleton instance scope confusion in JavaScript

本文关键字:范围 实例 单例 JavaScript      更新时间:2023-09-26

我正在学习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

我不明白为什么变量instance在启动singletonTest1时获得一些值。

创建模块SingletonTester时,也称为:

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

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

由于instance是由SingletonTester闭包封闭的属性,因此实例对于SingletonTester的整个存在都是活动的

旁注:单例模式主要是关于创建线程安全的静态实例,以便在进程之间共享。 由于JavaScript是单线程的,这显然不是问题。 相反,您可以保持简单,只使用全局变量。