In JavaScript there are so many different ways to inherit a super class. For example, Object.create, jQuery.extend, Child.prototype = new Parent(), and so on.
However, it’s not common to use __proto__ to create inheritance chain in javascript. Let me get to it right now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var Person = function(name) { this.name = name; } Person.prototype.sayMyName = function() { console.log('My name is ' + this.name); } // So we have Person class in javascript. // I want to create a Child class that inherits Person class using __proto__, so show me now! var Child = function() { // calling super class's constructor Person.apply(this, arguments); } // this is it. Child.prototype.__proto__ = Person.prototype; var child1 = new Child('Joshua'); child1.sayMyName(); // My name is Joshua |
So that does not look quite impressive. One cool thing about __proto__ is that any instance gets it when created. In javascript pretty much anything can be overwritten, which means after you create a regular object you can still make the instance inherit from a particular Class. Here’s a good example of late inheritance.
1 2 3 4 5 6 7 |
var child2 = {}; // oops I forgot to make that as Child's instance. However, __proto__ can help with the situation. child2.__proto__ = Child.prototype; child2.sayMyName(); // My name is undefined |
It sorta worked, but how about parent Class’ constructor execution? Unfortunately you will have to run one line of code as a late inheritance penalty.
1 2 3 |
Child.call(child2, 'Jesse'); child2.sayMyName(); // My name is Jesse |
That was a technique used by many old actionscript developers back in the days to create inheritance chain… We were cautious about its usage since it was undocumented feature and it could have been changed without telling anyone. I’m not sure if all browsers support that syntax, but that’s something good to know and understand how javascript works in my opinion anyways.
Some more good info on __proto__
http://coderkeen.com/old/articles/proto.html
Certainly the link’s got comprehensive details on proto. 🙂