Simply put: JS inheritance is a way to get existing properties and methods of existing objects. The main ways to implement js inheritance are:
1. Prototype-based inheritance
function Parent(name1){
this.name1 = name1
}
Parent.prototype.pMethod = function(){
console.log(this.name1)
}
function Child(name2, name1){
Parent.call(this, name1)
this.name2 = name2
}
Child.prototype.__proto__ = Parent.prototype
Child.prototype.cMethod = function(){
console.log(this.name2)
}
Copy the code
Summarized as an important JS formula:
Object.__proto__ === its constructor. PrototypeCopy the code
Class-based inheritance
With the concept of classes in ES6, you can declare a class through class and implement inheritance through the extends keyword.
class Parent{
constructor(name1){
this.name1 = name1
}
pMethod(){
console.log(this.name1)
}
}
class Child extends Parent{
constructor(name2, name1){
super(name1)
this.name2 = name2
}
cMethod(){
console.log(this.name2)
}
}
Copy the code