2020-06-12

inheritance

Inheritance of Object in JS

Disclaimer

This article is originally based on my understanding of this concept. No guarantee on the accuracy.😅

Prototype chain

Let subType’s prototype points to an instance of the superType;

1
SubType.prototype= new SuperType()

Problems:

  • The instance property of SuperType becoms the shared prototype property for SubType
  • There is no way to pass arguments to the constructor of superType

Constructor stealing

Calling the constructor of supertype inside the constructor of subtype.

1
2
3
4
function SubType(...arg){
//now it's avaliable to pass arguments to supertype
SuperType.call(this,arg)
}

Problems:

  • No access for Subtype to the prototype method/properties of the SuperType
  • The methods are defined inside the constructor which makes them instance method. Not shared with all instances;

Combination inheritance

Prototype chain + constructor stealing

1
2
3
4
5
function SubType (..args){
SuperType.call(this,args)
}
SubType.prototype = new SuperType()
SubType.prototype.constructor =Subtype;

Problems:

  • The constructor function always be called twice during the inheritance;

Prototypal inheritance

The constructor is not necessary to perform inheritance. It simply can be done by a object itself.

1
2
3
4
5
6
7
8
9
10
Object.create()
Object.prototype.create=(prototype)=>{
function F(){};
//points the prototype to the argument (an object)
F.prototype = prototype;
//return the instance of the temp constructor
return new F()
}
let Person = {greeting:'Hello'}
let Student =Object.create(Person)

Inheritance using constructor:

1
SubType = Object(SuperType.prototype)

Parasitic inheritance

Create a function only focus on encapsulation

1
2
3
4
5
6
7
8
9
10
11
function parasitic(prototype){
let object = Object.create(prototype);
object.method=function (){
console.log(this.name)
}
return object;
}
let super = {name:'super'}
let obj1= parasitic(super);
let obj2=parasitic(super);
obj1.method !=obj2.method;

Problems:

  • The methods are not shared with instances;

Parasitic combination

For combination inheritance, the constructor function was called twice.

The instance property of superType were created first to be the prototype property of subtype, (SubType.prototype = new Super())

then created as iinstance properties.(inside the constructor)

1
2
3
4
5
function inheritance(subType,superType){
let prototype=Object.create(superType.prototype);
prototype.construcotr = subType;
subType.prototype=prototype;
}

Mixing inheritance

JS dosen’t support multiple inheritance, but method of different class/object can be borrowed by mixing

1
2
3
4
5
6
7
8
9
10
11
12
13
let Student ={
study(book){
console.log('read'+book)
}
}
function Person(name){
this.name = name;
this.greeting=function(){
console.log(name)
}
}
let jack = new Person('jack')//jack Person {name:'jack'}
Obejct.assign(jack,Student);//jack Person {name: "jack", greeting: ƒ, study: ƒ}