JavaScript Inheritance

Posted on by By Nikhilesh, in Javascript | 0

JavaScript Inheritance

In my last post, I covered JavaScript Classes and now, I’ll continue with inheritance. JavaScript uses prototypal inheritance in contrast to classical. When a class is instantiated, it’s prototype is stored in __proto__ key of the object, which may in turn contain __proto__ from another parent class. This is called Prototype chaining. Lets have a look at what this means by an example.

The Base Class

Lets continue with the the example used in previous post. We a simple base class called Person

var Person = function (name, age){
    this.name = name,
    this.age = age 
};

Person.prototype.greet = function(){
    console.log('Hello, I\'m ' + this.name);
}

 

Inherited Student

Lets make a class called Student which inherits from Person

var Student = function(name,age){
        this.name = name,
        this.age = age 
};

//Inheritance
Student.prototype = Person.prototype;

 

When you run the following code, you’ll notice that Student has inherited the greet method of the Person class and that __proto__ of both a and b contains greet method.

var a = new Person("li", 22);
a.greet(); // Hello, I'm li
console.log (a); //Person {name: "li", age: 22, greet: function}

var b = new Student("Joe", 20);
b.greet(); // Hello, I'm Joe
console.log(b); //Student {name: "Joe", age: 20, greet: function}

inherit00

Now lets change the inheritance

Student.prototype = new Person();

 

And if you run the code again, you’ll see that similar results, but this time, __proto__ of b does not have the method greet but the __proto__ of __proto__ of b has the method greet.

var a = new Person("li", 22);
a.greet(); // Hello, I'm li
console.log (a); //Person {name: "li", age: 22, greet: function}

var b = new Student("Joe", 20);
b.greet(); // Hello, I'm Joe
console.log(b); //Student {name: "Joe", age: 20, greet: function}

inherit01

What Changed?

When we set the Student.prototype to new Person(), a new instance of Person was assinged to it, which had greet in its __proto__ and when the Student was initialized, the prototype was assigned to its __proto__.
Untitled

Conclusion

Don’t worry if you cannot get your head around this. It also took me a while to get hang of it. But once you understand it, it’s a very powerful tool.

logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments