Global variables should be reserved for objects that have system-wide relevance and they should be named to avoid ambiguity and minimize the risk of naming collisions. In practice this means you should avoid creating global objects unless they are absolutely necessary.
As we have already mentioned throughout the article, JavaScript does not support classes in its native form. Inheritance between objects is implemented using prototype-based programming.
It enables us to create objects which can serve as a prototype for other objects being created. The prototype object is used as a blueprint for each object the constructor creates.
As we have already talked about this in the previous sections, let’s show a simple example of how this pattern might be used.
var personPrototype = {
sayHi: function() {
console.log("Hello, my name is " + this.name + ", and I am " + this.age);
},
sayBye: function() {
console.log("Bye Bye!");
}
};
function Person(name, age) {
name = name || "John Doe";
age = age || 26;
function constructorFunction(name, age) {
this.name = name;
this.age = age;
};
constructorFunction.prototype = personPrototype;
var instance = new constructorFunction(name, age);
return instance;
}
var person1 = Person();
var person2 = Person("Bob", 38);
// prints out Hello, my name is John Doe, and I am 26
person1.sayHi();
// prints out Hello, my name is Bob, and I am 38
person2.sayHi();
Unfortunately JavaScript doesn’t provide namespace by default. So anything (function, method, object, variable) we create in JavaScript is global and we continue polluting that global namespace by adding more to that. But the good news is that we can create namespace in JavaScript and that too very easily. As we know, in JavaScript everything is an object and creating an object is very simple. We can achieve namespace very easily with some minor tweaks.
var MYAPPLICATION = {
calculateTax: function (item) {
return item * 1.40;
},
product: function (cost) {
this.cost = cost;
this.getCost = function(){
return this.cost;
};
},
doTaxCalculations: function () {
var p = new MYAPPLICATION.product(100);
alert(this.calculateTax(p.getCost()));
}
}
MYAPP.MODEL.PRODUCTS.product = function(cost) {
//cost is the private variable
var cost = cost;
return {
isTaxable: true,
getCost: function(){
return cost;
}
};
};