zoukankan      html  css  js  c++  java
  • Javascript中singleton的实现

          最好的实现:

    var langzi = window.langzi || {};
    langzi.singleton = window.langzi.singleton || (function () {
        var instance = null;
        var constructor = function () {
            return {
                id: 1,
                name: "test",
                getMessage: function () {
                    console.log("id:" + this.id + ", name:" + this.name);
                }
            };
        };

        return {
            getInstance: function () {
                if (instance == null) {
                    instance = constructor();
                }
                return instance;
            }
        };
    } ());

     测试代码如下:

    // test
    var s1 = langzi.singleton.getInstance();
    var s2 = langzi.singleton.getInstance();
    s1.getMessage();
    s2.getMessage();
    console.log(s1 == s2);

          按照Pro Javascript Design Pattern作者的说法,namespace都是singleton的应用。从广义来说,个人认为确实是的,但既然说到singleton,我觉得应该还是我上面的例子最具有代表性。 

  • 相关阅读:
    NHibernate错误集锦
    potree的第三方库
    potree的API说明文档
    potreeConverter之数据处理
    potreeConverter之环境配置
    SpringBoot读取配置文件信息
    SpringBoot启动tomcat失败
    AbstractRoutingDataSource动态切换数据源
    多数据源配置(Spring+mybatis)
    单一数据源配置(Spring+Mybatis)
  • 原文地址:https://www.cnblogs.com/Langzi127/p/2684848.html
Copyright © 2011-2022 走看看