Review the inheritance of JS

First provide a parent class (provide inherited properties)

function Father(name){
    
    
  this.name = name;
  this.sum = function(){
    
    
	alert(this.name)	
  }
}
Father.prototype.age = 38;

1. Prototype chain inheritance

function Son(){
    
    
  this.name = 'perter';
}
Son.prototype = new Father();// 最重要的!
var per = new Son();
console.log(per.age); // 38;
console.log(per instanceof Father);// true

Important: Make the prototype of the new instance equal to the instance of the parent class.
Features:
1. The inheritable properties of an instance include: the properties of the instance's constructor, the properties of the parent class's constructor, and the properties of the parent class's prototype. (The new instance will not inherit the properties of the parent class instance!)  
Disadvantages:
1. The new instance cannot pass parameters to the parent class constructor.      
2. Single inheritance.     
3. All new instances will share the properties of the parent instance. (The properties on the prototype are shared. If one instance modifies the prototype property, the prototype property of another instance will also be modified!)

2. Borrowing constructor inheritance (call, apply inheritance)

function Con() {
    
    
  Father.call(this, 'jhon');
  this.age = 12;
}
var con1 = new Con();
console.log(con1.age); // 12
console.log(con1.name); // jhon
console.log(con1 instanceof Father); //false

Key point: Use .call() and .apply() to introduce the parent class constructor into the subclass function (self-execution (copy) of the parent class function is done in the subclass function)
Features: 1. Only inherit the parent class constructor The properties of the parent class prototype are not inherited.
   2. Solve the shortcomings 1, 2, and 3 of prototype chain inheritance.
   3. You can inherit multiple constructor attributes (call multiple).
   4. In the child instance, parameters can be passed to the parent instance.
Disadvantages: 1, can only inherit the properties of the parent class constructor.
   2. It is impossible to reuse the constructor. (Re-call every time you use it)
   3. Each new instance has a copy of the parent class constructor, which is bloated.
The difference between call and apply:
The number of the second parameter of call is not fixed
. The second parameter of apply is an array. This array can be replaced by arguments

3. Combination inheritance (combination of prototype and call)

function Parent(value) {
    
    
this.val = value
}
Parent.prototype.getValue = function() {
    
    
console.log(this.val)
}
function Child(value) {
    
    
Parent.call(this, value)
}
Child.prototype = new Parent()

const child = new Child(1)

child.getValue() // 1
child instanceof Parent // true

Guess you like

Origin blog.csdn.net/Beth__hui/article/details/106015682