Other

Javascript单例实例

方案1 (闭包)

  • 实现语法
var App = function() {
    console.log("Initial ...");
    this.properties = {
        "uptime": new Date().getTime(),
        "show": function() {
            console.log("show ... => ", App.getInstance().properties.uptime);
        }
    };
}

App.getInstance = (function() {
    var instance;
    return function() {
        if (instance) {
            return instance;
        }
        // Build single instance
        return instance = new App();
    };
})();

console.log("Result1 => ", App.getInstance() === App.getInstance());
console.log("Result2 => ", App.getInstance().properties.uptime);
var timer1 = setTimeout(function() {
    App.getInstance().properties.show();
}, 1000);
  • 结果输出
Initial ...                                          VM9457:2
Result1 =>  true                                     VM9457:22
Result2 =>  1627529244788                            VM9457:23
show ... =>  1627529244788                           VM9457:6

留言

您的电子邮箱地址不会被公开。