學習Javascript並有一個關於全局變量的問題。從我的閱讀中,最推薦不要使用它們。但是,在基於類的javascripting中,這個不成文的規則是否仍然適用?例如:應該避免全局變量?
var width = 0;
var height = 0;
<!-- constructor -->
function Rectangle(){}
<!-- getters/setters -->
Rectangle.prototype.getWidth = function(){
return width;
}
Rectangle.prototype.setWidth = function(w){
width = w;
}
Rectangle.prototype.getHeight = function(){
return height;
}
Rectangle.prototype.setHeight = function(h){
height = h;
}
<!-- methods -->
Rectangle.prototype.area = function(){
return height * width;
}
var myRect = new Rectangle();
myRect.setWidth(5);
myRect.setHeight(4);
console.log(myRect.area()); //20
console.log(myRect.getWidth()); //5
myRect.setWidth(10);
console.log(myRect.getWidth()); //10
console.log(myRect.area()); //40
我熟悉Java以及對類,屬性和方法使用訪問修飾符的能力。是否因爲Javascript中不存在訪問修飾符,應該避免使用全局變量?
這是正確的答案 – 2012-02-02 16:11:09
this.width = w || 0; - 這是OR運算符的一個有趣用法。正確的是,如果沒有設置w,這將返回0? – worked 2012-02-02 18:50:35
@worked that's correct – fcalderan 2012-02-02 19:50:55