JavaScript- parasitic combined inheritance

The so-called parasitic combined inheritance, i.e., inheriting properties to the constructor, by prototypal inheritance inherited methods, as follows:

function inheritPrototype(sub,sup){
        var prototype = Object.create(sup.prototype);
        prototype.constructor = sub;
        sub.prototype = prototype;
    }

The first step is to create a copy of the super-type prototype, the second step is to make up for the loss of the prototype rewrite the default constructor property, the third step is to copy the copy to the subtype prototype.

To try how to call it, for example:

function Super(name){
        this.name = name;
        this.colors = ["red","blue","yellow"];
    }
    Super.prototype.sayName = function(){
        console.log(this.name);
    }
    function Sub(name){
        Super.call(this,name);
    }
    inheritPrototype(Sub,Super);

To put it plainly, it is to borrow the parasitic combined inherited inherited constructor + prototype style inheritance, but prototypal inheritance in the object method of transmission is not the object itself, but the prototype object.

Guess you like

Origin www.cnblogs.com/gehaoyu/p/11805084.html