Change before you have to.

JavaScript singleton pattern

2017-07-19

JavaScript 單例模式

以 OOP 角度而言,使用 constructor function 來建立物件時,每次的新物件都會指向不同的 reference,在某些情況下,我們需要使用單例模式確保不管建立幾個物件,這些物件都指向同一個 reference。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const Circle = (function() {
let instance
return function() {
if(instance) {
return instance
}
instance = this
// if you use new operator to make new object, you don't have to return any thing.
// the new object created wil be return imexplicitly
}
})()
const circle1 = new Circle()
const circle2 = new Circle()
console.log(circle1) // {}
console.log(circle2) // {}
circle1.color = 'blue'
console.log(circle1) // {color: 'blue'}
console.log(circle2) // {color: 'blue'}
console.log(circle1 === circle2) // true

首先使用 IIFE(Immediately Invoked Function Expression)


Blog comments powered by Disqus