Inheritance in JavaScript is called prototypal inheritance. Objects inherit from objects. When we create an object from a class,
[wp_ad_camp_5]
1 2 3 4 5 6 | function MyClass() { // The class }; var myObject = new MyClass(); |
it always inherits from
1 | MyClass.prototype |
In Java speak, this is like saying “any class inherits from Object class”.
1 2 3 | public class MyClass extends Object { ... } |
If we point MyClass.prototype to another object, e.g., new Person(), MyClass objects now inherit from Person object.
[wp_ad_camp_4]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function Person() { var _name = "Default Name"; this.getName = function() { return _name }; this.setName = function(v) { _name = v; }; }; function Student() { }; // Point Student.prototype to an Person object Student.prototype = new Person(); var student = new Student(); console.log(student.getName()); student.setName("Turreta rocks!"); console.log(student.getName()); |
Outputs:
1 2 | Default Name Turreta rocks! |
[wp_ad_camp_3]