Skip to content

Instantly share code, notes, and snippets.

@dreamline2
Last active September 16, 2015 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreamline2/5830cfa811a8a27a9866 to your computer and use it in GitHub Desktop.
Save dreamline2/5830cfa811a8a27a9866 to your computer and use it in GitHub Desktop.
singleton example -> create plus and minus to operate num
var operate = (function(){
// num is local variable, and we can via return api to manipulate num, no other external methods to manipulate num.
var num;
function createNum() {
var num = new Number(0);
return num;
}
return {
getNum: function () {
if (!num) {
num = createNum();
}
console.log(num)
return num;
},
plus: function () {
if (!num) {
num = createNum();
}
num++;
console.log(num)
},
minus: function () {
if (!num) {
num = createNum();
}
num--;
console.log(num)
}
}
})()
@dreamline2
Copy link
Author

singleton 稱為單體模式 ,為最常見的封裝模式!
主要是為提供了兩大功能

  1. 封裝變數,讓原本全域的變數變成區域變數,供區域操作使用。
  2. 建立命名空間(namespace),減少命名衝突(name collision)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment