Skip to content

Instantly share code, notes, and snippets.

@KalpasWang
Last active December 17, 2019 15:27
Show Gist options
  • Save KalpasWang/2c26310e6576c14f931ceb215c91b395 to your computer and use it in GitHub Desktop.
Save KalpasWang/2c26310e6576c14f931ceb215c91b395 to your computer and use it in GitHub Desktop.
單例模式
// 儲存在靜態屬性中的實體
function Universe() {
// do we have an existing instance?
if (typeof Universe.instance === 'object') {
return Universe.instance;
}
// proceed as normal
this.start_time = 0;
this.bang = "Big";
// cache
Universe.instance = this;
// implicit return:
// return this;
}
// testing
var uni = new Universe();
var uni2 = new Universe();
uni === uni2; // true
// 缺點是instance是public
/*** Instance in a Closure ***/
function Universe() {
// the cached instance
var instance = this;
// proceed as normal
this.start_time = 0;
this.bang = "Big";
// rewrite the contructor
Universe = function() {
return instance;
};
}
// testing
var uni = new Universe();
var uni2 = new Universe();
uni === uni2; // true
// 缺點是重新定義後的函式會失去初次定義到重新定義之間加在它身上的屬性
// adding to the prototype
Universe.prototype.nothing = true;
var uni = new Universe();
// again adding to the prototype
// after the initial object is created
Universe.prototype.everything = true;
var uni2 = new Universe();
// only the original prototype was
// linked to the objects
uni.nothing; // true
uni2.nothing; // true
uni.everything; // undefined
uni2.everything; // undefined
// that sounds right:
uni.constructor.name; // "Universe"
// this looks weird
uni.constructor === Universe; // false
// 這個實作讓原型和建構式指標正常運作
function Universe() {
// the cached instance
var instance;
// rewrite the constructor
Universe = function Universe() {
return instance;
};
// carry over the prototype properties
Universe.prototype = this;
// the instance
instance = new Universe();
// reset the constructor pointer
instance.constructor = Universe;
// all the functionality
instance.start_time = 0;
instance.bang = "Big";
return instance;
}
// testing
var uni = new Universe();
var uni2 = new Universe();
uni === uni2; // true
// adding to the prototype
Universe.prototype.nothing = true;
var uni = new Universe();
// again adding to the prototype
// after the initial object is created
Universe.prototype.everything = true;
var uni2 = new Universe();
// only the original prototype was
// linked to the objects
uni.nothing; // true
uni2.nothing; // true
uni.everything; // true
uni2.everything; // true
// that sounds right:
uni.constructor.name; // "Universe"
uni.constructor === Universe; // true
// 另一種解法
var Universe;
(function() {
var instance;
Universe = function Universe() {
if (instance) {
return instance;
}
instance = this;
// all the functionality
this.start_time = 0;
this.bang = "Big";
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment