單例模式
了解什么是模塊
```
function CoolModule() {
var something = "cool";
var another = [1, 2, 3];
function doSomething() { console.log( something );
}
function doAnother() {
console.log( another.join( " ! " ) );
}
return {
doSomething: doSomething, doAnother: doAnother
};
}
var foo = CoolModule(); foo.doSomething(); // cool
foo.doAnother(); // 1 ! 2 ! 3
```
這個模式在 JavaScript 中被稱為模塊,最常見的實作模塊模式的方法通常被稱為模塊暴露, 這里展示的是其變體,
單例模式:當只需要一個實體時,可以對這個模式進行簡單的 改進來實作單例模式,
```
var foo = (function CoolModule() { var something = "cool";
var another = [1, 2, 3];
function doSomething() { console.log( something );
}
function doAnother() {
console.log( another.join( " ! " ) );
}
return {
doSomething: doSomething, doAnother: doAnother
}; })();
foo.doSomething(); // cool foo.doAnother(); // 1 ! 2 ! 3
```
- 利用自執行函式,立即呼叫這個函式并將回傳值直接賦值給單例的模塊實體識別符號 foo,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/227120.html
標籤:其他
上一篇:JS的原型和繼承,讓javascript功力再上一層
下一篇:解決vue頁面重繪,資料丟失
