Skip to content

Instantly share code, notes, and snippets.

@MrKou47
Last active July 28, 2017 03:57
Show Gist options
  • Save MrKou47/07195c5a5d2787ae413ad4bfab7716f6 to your computer and use it in GitHub Desktop.
Save MrKou47/07195c5a5d2787ae413ad4bfab7716f6 to your computer and use it in GitHub Desktop.
单例模式
/**
* 单例模式
* 避免重复创建相同对象
* example:
* let a = new TestClass();
* let b = new TestClass();
* a === b // false
* 如何a===b 为 true
*/
// ----------- achieve first -----------
let TestClass = {
say: function () {
console.log('say something!');
}
}
let a = TestClass;
let b = TestClass;
console.log(a===b); // 指向同一引用
// ----------- achieve second -----------
function TestClass2() {
if (TestClass2.unique) return TestClass2.unique;
TestClass2.unique = this;
}
TestClass2.prototype.say = function () {
console.log('say something!');
}
let c = new TestClass2();
let d = new TestClass2();
console.log(c === d);
// ----------- achieve third -----------
const TestClass3 = (function () {
let instance;
function TestClass3() {
}
TestClass3.prototype.say = function () {
console.log('say somthing!');
}
if (instance === undefined) instance = new TestClass3;
return instance;
})();
let e = TestClass3;
let f = TestClass3;
console.log(e === f);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment