也就是和C#、JAVA等語言一樣,變數也會有Private、Public的差別!
先介紹 global variable(全域變數)和 local variable(私有變數)的差別:
- global variable
直接宣告並隸屬於window物件的變數
var a = 4;
function myFunction() {
return a * a;
} - local variable
宣告在function內的變數
function myFunction() {
var a = 4;
return a * a;
}
var counter = 0;
function yourfunction() {
counter =5;
counter =5;
//do something....
}
var counter = 10;
function othersfunc() {
counter += 1;
}
add();
add();
add();
// the counter is now equal to 13
var counter = 10;
function othersfunc() {
counter += 1;
}
add();
add();
add();
// the counter is now equal to 13
function add() {
var counter = 0;
counter += 1;
}
add();
add();
add();
// the counter should now be 3, but it does not work !
var counter = 0;
counter += 1;
}
add();
add();
add();
// the counter should now be 3, but it does not work !
因此就要使用inner function了:
function add() {
var counter = 0;
function plus() {counter += 1;}
plus();
return counter;
}
var counter = 0;
function plus() {counter += 1;}
plus();
return counter;
}
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
// the counter is now 3
var counter = 0;
return function () {return counter += 1;}
})();
add();
add();
add();
// the counter is now 3
再明確講一次封裝重點要件:
- 自發執行函數 (function(){ //do something })()
- 在上述函數內宣告私有變數 var counter = 0;
- return function(){} 給指定物件 var add
- 完工!
沒有留言:
張貼留言