Javascript – Inheritance
There are many ways to perform inheritance using objects in javascript. I recommend reading chapter 3 and 4 from Professional Javascript for Web Developers” to get a full understanding of how the language can be utilized for inheritance.
Below I have listed a hybrid method that incorporates using the call() method and prototype chaining to simulate inheritance that matches closely to how you would use it in a typed language like Java or C#.
function File(name, path) {
this.name = name;
this.path = path;
}
File.prototype.getName = function() { return this.name; }
File.prototype.setName = function(name) { this.name = name; }
File.prototype.getPath = function() { return this.path; }
File.prototype.setPath = function(path) { this.path = path; }
Using the prototype keyword, means that the method is assigned to the File class. Without it, the function would be a new instance for every instantiated File object.
The following subclass utilizes the call() method which in this case is analogous to the super keyword in java or the base keyword in C#.
It then uses prototype chaining to assign/copy all the prototype functions of File to itself, before defining further functions that relate specifically to itself.
function ExcelFile(name, path, numberOfWorksheets) {
File.call(this, name, path); // equivalent to calling base(name, path)
this.numberOfWorksheets = numberOfWorksheets;
}
// this is how you inherit all the prototype values of the base class.
// ensure to place this before defining new functions as this will blat out
// all prototype functions currently declared for the class.
ExcelFile.prototype = new File();
ExcelFile.prototype.getNumberOfWorksheets =
function() { return this.numberOfWorksheets; }
ExcelFile.prototype.setNumberOfWorksheets =
function(numberOfWorksheets) { this.numberOfWorksheets =
numberOfWorksheets; }
The following shows how you would instantiate your classes and prove that the inheritance worked.
var file = new File("RecipeDetails.txt", "c:/temp");
var excelFile = new ExcelFile("Business.xls", "c:/temp", 6);
alert(excelFile instanceof File);
alert(excelFile instanceof ExcelFile);
Great article B – I didn’t know any of that stuff. My experience creating new classes in JS is very limited!