OOP2: How to inherit?

There are two ways to inherit from parent class in JS:
This creates a new object and its _proto_ directs to the argument. Then a prototype chain is formed and all the properties and methods in the prototype can be visited.

function Person(){this.a = 1};
Student.prototype = Object.create(Person.prototype);
// The _proto_ directs to an object whose _proto_ points to Person.prototype
// Student.prototype.a cannot be visited.

In case Object.create() is incompatible.

if (!Object.create) {
   Object.create = function(proto) {
        var F = function(){};
        F.prototype = proto;
        return new F();
New creates an instance with its instance’s _proto_  directing to its constructor’s prototype. Also, Constructor.apply(instance, arguments) will be implicitly invoked.

Student.prototype = new Person();
// The _proto_ directs to an instance whose _proto_ points to Person.prototype
// Student.prototype.a can be visited

In these two case Student.prototype.constructor will be Person during the inherit process. So below is necessary when checking the object type.

Student.prototype.constructor = Student;

The difference between above two methods is when you new an instance, the arguments can be  an dilemma as you might don’t really have some clear arguments to form in, so it can be a bit strange. Object.create() can only inherit the methods and properties in prototype while new inherits all. Object.create() only calls Person once and avoids adding useless properties. Thus using Object.create() is suggested.

Person.prototype.a = 2;
Student.prototype = Object.create(Person.prototype);
Student.prototype = new Person();
console.log(Student.prototype.a);//1 as this.a

Through this feature, a bug can be fixed(similar to the hole in OOP4 but this is a particular case).

function SuperType(){
function SubType(){;// equals this.colors=['red'];
//without this statement, instance1.colors and instance2.colors will be pointing to SubType.prototype.colors
SubType.prototype = new SuperType();
var instance1 = new SubType();
var instance2 = new SubType();
console.log(instance1.colors === instance2.colors);//false

To sum up, to inherit perfectly use apply in subclass definition and use Object.create() to create prototype chain are the best match, plus setting the constructor value. And better not define properties in superclass.prototype.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s