Learning Javascript and have a question about global variables. From my reading, most recommend not to use them. However, in class based javascripting, does this unwritten rule still apply? For instance:
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
I'm familiar with Java and the ability to use access modifiers for classes, properties and methods. Is it because access modifiers do not exist in Javascript that globals should be avoided?
You would probably use this code instead
<!-- constructor -->
var Rectangle = function(w, h) {
this.width = w || 0;
this.height = h || 0;
}
<!-- getters/setters -->
Rectangle.prototype.getWidth = function( ) { return this.width; }
Rectangle.prototype.setWidth = function(w) { this.width = w; }
Rectangle.prototype.getHeight = function() { return this.height; }
Rectangle.prototype.setHeight = function(h) { this.height = h; }
<!-- methods -->
Rectangle.prototype.area = function(){
return this.height * this.width;
}
var myRect = new Rectangle(5, 4);
console.log(myRect.area()); //20
console.log(myRect.getWidth()); //5
myRect.setWidth(10);
this.width
and this.height
, otherwise you will modify the global width and height variables and those values won't be tied to the single instance of Rectangle.var Rectangle = function(w, h) { ... }
rather than function Rectangle() { ... }
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With