1. 程式人生 > >寄生組合式繼承

寄生組合式繼承

col 利用 cti pro per tor log func console

實例1:

function SuperType(name){
        this.name = name;
        this.colors = [‘red‘,‘green‘,‘blue‘];
    }

    SuperType.prototype.sayName = function(){
        console.log(this.name);
    }
    
    function SubType(name,age){
        SuperType.call(this,name);
        this.age = age;    
    }
    
    
function inheritPrototype(SubType,SuperType){ SuperType.prototype.constructor = SubType;//把上邊的兩個函數合並 SubType.prototype = SuperType.prototype; } /** 公用的構造函數 function SubType(name,age){ this.name = name; this.colors = [‘red‘,‘green‘,‘blue‘]; this.age = age; }
*/ inheritPrototype(SubType,SuperType); SubType.prototype.sayAge = function(){ console.log(this.age); } var p1 = new SubType(‘zhangsan‘,89); p1.sayName(); p1.sayAge(); console.log(p1.colors); console.log(p1);

這個是利用call()和SuperType.prototype.constructor = SubType;//把上邊的兩個函數合並函數公用一個構造函數

寄生組合式繼承