方案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