学习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