寄生组合式继承 js

寄生组合式继承是集寄生式继承和组合继承的优点于一身,是基于类型继承最有效的方式
function object(o){
    function F(){};
    F.prototype = o;
    return new F();
}

function inheritPrototype(subType,superType){
    var prototype = object(superType.prototype);
    prototype.constructor = subType;
    subType.prototype = prototype;
}

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

SuperType.prototype.sayName = function(){
    alert(this.name)
}

function SubType(name,age){
    SuperType.call(this,name);
    this.age = age;
}

inheritPrototype(SubType,SuperType);

SubType.prototype.sayAge = function(){
    alert(this.age);
}

var person1 = new SubType("china",1);
console.log(person1.name);   // "china"
console.log(person1.colors);  // ["red","yellow","green"]

person1.sayAge(); // 1

 

posted on 2017-07-04 14:54  CNundefined  阅读(217)  评论(0编辑  收藏  举报