來源
JavaScript uses functions to manage scope.
這些都是 Global variable
myglobal = "hello"; // antipattern
console.log(myglobal); // "hello"
console.log(window.myglobal); // "hello"
console.log(window["myglobal"]); // "hello"
console.log(this.myglobal); // "hello"
這樣不好:
function sum(x, y) {
// antipattern: implied global
result = x + y;
return result;
}
需改成這樣:
function sum(x, y) {
var result = x + y;
return result;
}
這樣不好: because a
is local but b
becomes global
function foo() {
var a = b = 0;
// ...
}
需改成這樣:
var a = (b = 0); // or
function foo() {
var a, b;
// ... a = b = 0; // both local
}
待續...
沒有留言:
張貼留言