JavaScript中的单例模式 [英] Singleton pattern in JavaScript

查看:78
本文介绍了JavaScript中的单例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个非常受欢迎的JavaScript单例模式实现示例:

Below is an example of a very popular implementation of the JavaScript Singleton pattern:

var mySingleton = (function() {
    var instance;

    function init() {
        function privateMethod() {
            console.log("I am private");
        }
        var privateVariable = "Im also private";
        var privateRandomNumber = Math.random();
        return {
            publicMethod: function() {
                console.log("The public can see me!");
            },
            publicProperty: "I am also public",
            getRandomNumber: function() {
                return privateRandomNumber;
            }
        };
    };

    return {
        getInstance: function() {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
})();

我已经考虑了一段时间了,当我真的不了解这种复杂性的需要时我们可以使用以下简单代码获得相同的结果:

I have been thinking about it for a while and don't really understand the need of this complexity when we can achieve the same result with this simple code:

singleton = (function() {
    var obj = {
        someMethod: function() {}
    }

    return obj;
}());

我在这里俯瞰什么吗?

推荐答案

是的,在大多数情况下,您不需要这种复杂性,只需这样做

Yes, in most cases you don't need this complexity, and would just do

var singleton = {
    someMethod: function() {}
};

但是,带有 getSingleton 函数的模式确实有一个优点:仅在调用函数时(第一次)构造对象,而不是在实际需要该对象之前构造该对象。根据对象的复杂程度,这可以改善内存使用率和程序的启动时间。基本上是延迟加载模块。

However, the pattern with that getSingleton function does have one advantage: The object is only constructed when the function is called (for the first time), not before the object is actually needed. Depending on the complexity of the object, this can improve memory usage and startup time of your program. It's basically lazy-loading the module.

这篇关于JavaScript中的单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆