Js inheritance has two kinds, one is ES5 inheritance, the other is ES6 class inheritance.
ES5 inheritance is mainly inheritance by modifying the stereotype chain. In essence, create an instance object of the subclass, this, and then add the Parent class’s methods to this (parent.apply (this)). Class inherits from external, essentially adding the properties and methods of the superclass object to this (so you must call super first), and then modifying this with the constructor of the subclass.
The inherited prototype chain
class A {}
class B extends A {}
b.__proto__ === B.prototype
B.prototype.constructor === B;
B.__proto__ === A;
B.prototype.__proto__ === A.prototype
Copy the code
Code to implement ES5 inheritance
Two main ways are listed
- Common prototype chain inheritance
If this. Name in Person is a reference type, all instances of Man will share it. If one instance changes it, the other instance will get a different result.
function Person(name) {
this.name = name;
this.getName = () = > {
return this.name;
};
}
Person.prototype.setName = function(name) {
this.name = name;
};
function Man(name){
this.sex='male';
this.getSex = () = > {
return this.sex;
};
}
//* Modify the prototype chain directly
Man.protoType = new Person('parameters');
Man.protoType.constructor = Man;
Copy the code
- Parasitic inheritance (recommended)
function Person(name) {
this.name = name;
this.getName = () = > {
return this.name;
};
}
Person.prototype.setName = function(name) {
this.name = name;
};
function Man(name){
Person.call(this,name);// Same as super in class inheritance
this.sex='male';
this.getSex = () = > {
return this.sex;
};
}
const protoType = Object.create(Person.prototype);
protoType.constructor = Man;
Man.protoType = protoType;
Copy the code
Object.creat: This method takes two arguments: an Object that acts on the prototype of the new Object and (optionally) an Object that defines additional properties for the new Object;