Please indicate the source for reprinting
In JavaScript, there are roughly five types of inheritance of objects.Namely:
- Constructor Binding
- Prototype Chain Inheritance
- Copy Inheritance
- Class for ES6
- Classic Inheritance (using empty objects as intermediaries)
Classic inheritance applies to inheritance between objects
The following is a detailed description:
Define two constructors, Animal and at first
function Animal(){ this.species = "Animal"; } function Cat(name,color){ this.name = name; this.color = color; }
There are two functions defined above, one is Cat and the other is Animal, how can Cat inherit Animal?
1. Constructor Binding
Use the call or apply method to bind the constructor of the parent object to the child object.
function Cat(name,color){ Animal.apply(this, arguments); this.name = name; this.color = color; } var cat1 = new Cat("Big hair","yellow"); alert(cat1.species); // Animal
2. Prototype Chain Inheritance
Using the prototype property directly, set the prototype of Cat.prototype to an Animal instance or Animal.prototype
// Point to Animal Instance Object.setPrototypeOf(Cat.prototype, new Animal()) /* * The previous line can also be written like this * Cat.prototype.__proto__ = new Animal(); */ var cat1 = new Cat("Big hair","yellow"); alert(cat1.species); // Animal // Point to Animal.prototype // Here's an improvement on Animal, putting the same properties into prototype function Animal(){ } Animal.prototype.species = "Animal"; Object.setPrototypeOf(Cat.prototype, Animal.prototype) /* * The previous line can also be written like this * Cat.prototype.__proto__ = Animal.prototype */ var cat1 = new Cat("Big hair","yellow"); alert(cat1.species); // Animal
3. Copy Inheritance
Copies all properties and methods of the parent object into the child object.
var p = Parent.prototype; var c = Child.prototype; for (var i in p) { c[i] = p[i]; }
4. Class Inheritance
Class can be inherited through the extends keyword, which is much clearer and more convenient than ES5's inheritance by modifying the prototype chain.
// Call super() in constructor class Parent { constructor (x, y) { this.x = x this.y = y } test = 'test' } class Child extends Parent { constructor (x, y, z) { super(x,y) this.z = z } } let child = new Child(1, 2, 3) child.test // test
5. Classic Inheritance (using empty objects as intermediaries)
Suitable for inheritance between objects
let a = { test: 'name' } // Objects created by object literals have no prototype // a.prototype === undefined // a let b = { name: 'test' } function C() {} C.prototype = a b = new C() b.test // name
In addition to the five common ways of inheriting objects, you can also combine them to achieve inheritance.
Reference material
Welcome to visit me Personal website