Eight kinds JS prototype inheritance approach the front of a compulsory interview

What is js inheritance?

Definitions

        If a class and properties can be reused or another class method, it is called inheritance.

        Most object-oriented languages ​​support inheritance.

Features: 

       Subclass can use all the features of the parent class, and to expand on these functions.

       The most important advantage of inheritance is code reuse, to build large-scale software systems.

Prototype chain to inherit (traditional form)

Disadvantages: 

        Excessive inherits the properties of useless

Grand.prototype.lastName = 'chen'
function Grand() {}
var grand = new Grand();
Father.prototype = grand;
function Father() {    
    this.name = 'hehe';
}
var father = new Father();
Son.prototype = father;
function Son() {}
var son = new Son();

复制代码

Borrowing Constructor (formula inherited class)

advantage:

        You can pass parameters

Disadvantages:

        You can not inherit borrow constructor prototype

        Every constructor should take a multi-function 

function Person(name, age, sex) { 
    this.name = name;
    this.age = age;
    this.sex = sex;
}
function Student(name, age, sex, grade) {
    Person.call(this, name, age, sex);
    this.grade = grade;
}
var student = new Student('hehe', 40, 'male', 18);复制代码

Combined succession (popular terms that prototype prototype inheritance chain properties and methods of using borrowed constructor of the instance attribute inheritance)

advantage:

        Avoid the chains and prototype constructors defects fused their advantage JavaScript has become the most common mode of inheritance

Disadvantages:

        Two properties exist on the same instance and prototype    

Father.prototype.getfaName = function() {  
    console.log(this.faName);
}
function Father(name) {    
    this.faName = 'father';
}
Child.prototype = new Father();
Child.prototype.constructor = Child;
function Child(args) {    
    this.chName = 'child';
    Father.apply(this, []);
}
var child = new Child(); 复制代码

Prototypal inheritance    

Disadvantages:

        You can not just change their prototype

function create(o){
    function F(){};
    F.prototype = o; 
    return new F();        
}        
var Person = {
    name:'me',            
    hobbies:['riding', 'swimming']  
}
var anotherPerson = create(Person);
var anotherPerson2 = create(Person);
anotherPerson.name = 'her';
anotherPerson.hobbies.push('dancing');        
console.log(anotherPerson2.name, anotherPerson2.hobbies); // her ["riding", "swimming", "dancing"]复制代码

Parasitic inheritance

Disadvantages:

        With borrowed constructor patterns, each time you create an object is created again method.

function createObj(o){   
    let clone = Object.create(o);            
    clone.sayName = function(){ 
        console.log('hi');            
    }
    return clone        
}        
let person = {            
    name:"JoseyDong",            
    hobbies:["sing","dance","rap"]        
}        
let anotherPerson = createObj(person);        
anotherPerson.sayName(); // => hi复制代码

The Holy Grail mode (a combination of parasitic inheritance)  

// 第一种写法
function inherit(Target, Origin) {   
    // 使用F空函数当子类和父类的媒介 是为了防止修改子类的原型对象影响到父类的原型对象 
    function F() {}
    F.prototype = Origin.prototype;
    Target.prototype = new F(); 
    Target.prototype.constructor = Target; // 防止new的时候 返回实例的构造函数指向混乱  
    Target.prototype.uber = Origin.prototype; // 寻找继承的原型是谁
}

// 第二种写法 采用立即执行函数和闭包的形式
var inherit = (function() {
    function F() {}    
    return function(Target, Origin) {   
        F.prototype = Origin.prototype;
        Target.prototype = new F(); 
        Target.prototype.contructor = Target; 
        Target.prototype.uber = Origin.prototype;
    }
})()复制代码

Object masquerading

Disadvantages:

         But there is a problem posing objects, attributes of the parent class when the same, will be defined later coverage property as previously defined, therefore, an object posing way to support parent class attributes is not the same situation is more reasonable.

         Every constructor should take a multi-function

function Father(color) {        
    this.color = color;        
    this.showColor = function () {            
        alert(this.color);        
    }    
}    
function Father1(color) {        
    this.color1 = color;        
    this.showColor1 = function () {            
        alert(this.color1);        
    }    
}    
function Child(color, color1) {        
    this.Method = Father;        
    this.Method(color);        
    delete this.Method;        
    
    this.Method = Father1;        
    this.Method(color1);        
    delete this.Method;    
}    
var child = new Child("wu", "zhao");    
child.showColor();复制代码

ES6 the wording extends inheritance

class Plane {    
    static alive() {        
        return true;    
    }    
    constructor(name) {        
        this.name = name || '普通飞机';        
        this.blood = 100;    
    }    
    fly() {        
        console.log('fly');    
    }
};
class AttackPlane extends Plane{    
    constructor(name) {        
        super(name);        
        this.logo = 'duyi';    
    }    
    dan() {        
        console.log('bububu');    
    }
}
var oAp = new AttackPlane('攻击机');
console.log(oAp);复制代码

note: 

        The subclass must call the super method in the constructor method, otherwise it will error when creating a new instance. This is because the subclass does not own this object, but this object inherits the parent class, before processing it, if you do not call the super method, the subclass will not get this object. Therefore, only after calling super, you can use this keyword.

Summary ES5 ES6 inherited the difference between?

ES5 essence of inheritance mechanism is to create an object instance of this subclass, then add to this parent class above (Parent.call (this)).

ES6 essence of inheritance mechanism is to create an object instance of this parent class (you must first call the super () method), then use the constructor subclass modify this.

Your praise is my point of continuous output power of hope to help them to learn to have any problems with each other below a certain reply message 


Reproduced in: https: //juejin.im/post/5ceca322f265da1bd6058416

Guess you like

Origin blog.csdn.net/weixin_33933118/article/details/91463018