【问题标题】:Singleton instance scope confusion in JavaScriptJavaScript 中的单例实例范围混淆
【发布时间】:2016-01-20 12:04:48
【问题描述】:

我正在学习 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 时会获得一些值。

【问题讨论】:

  • 在 JS 中,不需要Singleton,只需要使用全局变量即可。
  • 第二个^,但如果你仍然想要一个单例仿真,那么谷歌搜索“javascript单例执行器”。有一些 Git 项目可以做到这一点。无论如何都没有正确的意义。 JS 就是 JS。
  • @DavinTryon 这已经是一个单例模式,它工作正常。我的困惑是,当singletonTest1 启动时,instance 变量怎么会有值。至少在评论前阅读问题。
  • @Ingmars 问题不是关于我想要单例模式,而是关于别的东西。我想问为什么instance 变量在启动singletonTest1 时仍然存在。
  • @BharatSoni 之所以有效是因为SingletonTester 是一个全局变量。

标签: javascript design-patterns singleton


【解决方案1】:

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

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

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

由于instance 是一个被SingletonTester 闭包封闭的属性,因此在SingletonTester 的整个存在期间实例是活动的

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

【讨论】:

  • 啊,现在我明白了,很困惑。当然是闭包。非常感谢戴文。
猜你喜欢
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
相关资源
最近更新 更多