【发布时间】:2012-02-25 07:09:24
【问题描述】:
学习 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 中不存在访问修饰符,所以应该避免使用全局变量?
【问题讨论】:
标签: javascript