js 簡(jiǎn)單的單例寫(xiě)法
話不多說(shuō)拧额,上代碼
let instance = null;
class TClass {
public a: string;
constructor(str) {
if (!instance) { // singleton-design pattern
instance = this;
}
instance.a = str;
return instance;
}
}
// ------------------------------------------------
test('singleton-design test', t => {
const a = new TClass('3');
const b = new TClass('4');
t.is(a.a, '4')
t.is(a, b)
})
歡迎拍磚
大前端知識(shí)庫(kù)收集分享 www.rjxgc.com 壹玖零Tech
搜羅各種前后端奇淫技巧帆焕,花式編程思想肪凛,日日更新胶背,速來(lái)圍觀吧...