面向对象的程序设计(九)寄生组合式继承

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", "blue"];
}

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 instance1 = new SubType("Tom", "22");
instance1.colors.push("black");
console.dir(instance1);

var instance2 = new SubType("Lucy", "25");
console.dir(instance2);

 

posted @ 2013-07-07 16:15  金帛  阅读(227)  评论(0编辑  收藏  举报