Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should global variables be avoided?

Tags:

javascript

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?

like image 920
worked Avatar asked Dec 13 '22 05:12

worked


1 Answers

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);
  1. width and height should be 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.
  2. it's better use a function expression than a function declaration for the constructor function: var Rectangle = function(w, h) { ... } rather than function Rectangle() { ... }.
  3. You can also wrap all code inside an immediately self executed function so to completely avoid the global namespace pollution (look at jAndy answer)
  4. Initial width and height of your object can be passed in the constructor function for initialization (otherwise width and height are set to 0 - or other any value - by default).
  5. These rule are definitely written (see for reference Javascript : the good parts by D.Crockford).
like image 50
Fabrizio Calderan Avatar answered Dec 14 '22 18:12

Fabrizio Calderan