javascript - JavaScript 中的单例实例范围困惑

标签 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

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

最佳答案

当模块 SingletonTester创建后,又称为:

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

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

instance是由 SingletonTester 关闭的属性(property)闭包,实例在 SingletonTester 的整个存在期间活着 .

旁注:单例模式主要是创建线程安全的静态实例以跨进程共享。由于JavaScript是单线程的,这显然不是问题。您可以让事情变得简单,只使用全局变量。

关于javascript - JavaScript 中的单例实例范围困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34899590/

相关文章:

javascript - 谷歌分析如何跟踪用户退出

c++ - 如何在没有 OO 的情况下关联值(value)和功能

Lua:在字符串中查找十六进制值

java - Spring 测试上下文最佳实践

c++ - 基类如何禁用派生类的构造函数

singleton - 对于带有参数的构造函数,goog.addSingletonGetter() 是否有变体?

javascript - 使用递归搜索对对象中的数组进行排序

javascript - Node.JS 中的同步 "GET"

模板化单例的 C++ 工厂

javascript - AngularJS - 如何获取状态解析函数内的状态名称以加载 Controller 文件?