Javascript Inheritance
Posted on November 1st, 2011, by Cristian in Javascript & jQueryJavaScript is a bit confusing for developers coming from Java or C++, as it’s dynamic and does not provide a class implementation, although the keyword class is a reserved keyword and cannot be used as either a variable name or a property. JavaScript inheritance uses just three key ideas:
- An object’s methods (like all properties) are found by walking up the object’s prototype chain;
- The entries in the prototype chain are references to ordinary objects;
- Object.create() or the new operator creates objects with a longer prototype chain.
Here is a simple Javascript inheritance example to learn from:
var user;
function Person (name) {
this.name = name;
}
Person.prototype.hello = function() {
console.log('Hello', this.name);
};
// Student inherits from Person
function Student (name) {
this.name = name;
}
Student.prototype = new Person;
user = new Student('George');
// This method was defined on Person
user.hello();
If you are interested to read more about prototype chains check here: Inheritance and the prototype chain.
