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 | function SubType(...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 | function SubType (..args){ |
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 | Object.create() |
Inheritance using constructor:
1 | SubType = Object(SuperType.prototype) |
Parasitic inheritance
Create a function only focus on encapsulation
1 | function parasitic(prototype){ |
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 | function inheritance(subType,superType){ |
Mixing inheritance
JS dosen’t support multiple inheritance, but method of different class/object can be borrowed by mixing
1 | let Student ={ |