Introduction
To simulate the OO class feature and implement the inheritance functionality in JavaScript, we have the below methods.
Methods
1. Inherit by calling parent constructor function
Using this method, all the properties and methods of parent function will be copied to the child objects.
Cons
- It will cost more memory if the parent function has lots of properties and methods or the inheritance chain is long.
- The prototype chain is not correct.
1 | function Animal(species){ |
In this case, the prototype chain will be:
new Cat() ----> Cat.prototype ----> Object.prototype ----> null
2. Inherit with one parent object
Using this method, one parent object will be created to save all the properties and methods of parent function, and the parent object is linked to __proto__
property of the child objects.
Pros:
- It will cost less memory when creating new child objects if the parent function has lots of properties and methods or the inheritance chain is long.
- The prototype chain is correct.
Cons:
- It will cost more memory when defining the child function.
- Since one parent object is linked to multiple child objects, the change to the parent object will affect multiple child objects.
1 | function Animal(species){ |
In this case, the prototype chain will be:
new Cat() ----> Cat.prototype ----> Animal.prototype ----> Object.prototype ----> null
3. Inherit with new function object - Recommended
Using this method, all the properties and methods of parent function will be copied to the child objects.
Pros:
- It will cost less memory when defining the child function, since only one blank function object is created.
- The prototype chain is correct.
- The change to one child object will not affect other child objects.
Cons:
- It will cost more memory when creating new child objects, since all the properties and methods of parent function will be copied to the child objects, instead of linking one parent object to the child objects.
1 | function Animal(species){ |
In this case, the prototype chain will be:
new Cat() ----> Cat.prototype ----> Animal.prototype ----> Object.prototype ----> null
Notes
- When create a new object using constructor function, the
__proto__
of the new created object will point to the same object ofConstructorFunction.prototype
.
1 | function Animal(species){ |
- We can create a common function for the inheritance in the third method.
1 | function Animal(species){ |
- We can define the new methods for the parent function and child function, in the prototype of the constructor function.
1 | Animal.prototype.getspecies = function(){ |
Reference
http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance.html
Prototype Inheritance by Liao Xue Feng