【代码整理】JavaScript的寄生组合式继承

代码源于《JavaScript高级程序设计》。

看书时感觉有点乱,遂把寄生组合式继承的代码稍稍整理一下,以备以后参考。

<script type="text/javascript">
    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", "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 sub = new SubType('My JavaScript',11);
    sub.sayName();
    sub.sayAge();
    alert(sub.colors);
</script>


你可能感兴趣的:(JavaScript,js,代码,继承,寄生组合)