Javascript deal with inheritance through prototypes; in alternative there are libraries like Klass and Selfish.js.
Basically you need to do two things:
Here's an example:
function Parent(age){ this.age = age; // Ignored because overridden this.showAge = function(){ // Ignored because overridden document.write("Showing something"); } } function Son(age){ // Call the superclass constructor Parent.call(this, age); // Method created every time the constructor is called this.showAge = function(){ document.write("The age is " + this.age + "<br/>"); } } Son.prototype = Object.create(Parent.prototype); Son.prototype.name = "Bob"; // Method created only once, but it can't see "age" Son.prototype.showSomething = function() { document.write("Name : " + this.name + "<br/>"); } function Grandson(age){ // Call the superclass constructor Son.call(this, age); this.age = age + 1; } // Inherit Son (makes showSomething() visible) Grandson.prototype = Object.create(Son.prototype); // Example of a Grandson instance var gs = new Grandson(14); gs.showAge(); gs.showSomething();
You should also avoid bad practices like:
1) Son.prototype = Parent.prototype.
This would make every change in the child also visible into the parent and that's not what you want, isn't it?
2) Son.prototype = new Parent();
The main problem here is that you can't pass parameters to the constructor, because we are using Parent.call(params).
The correct solution is:
childObj.prototype = Object.create(parentObj);
In addition, you can also set the constructor:
Grandson.prototype.constructor = Grandson;
But this operation in itself doesn't do anything, because this property is not used internally. This might be useful if you need to create a library or you need for some reasons to read this property.
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.