JS寄生组合式继承

来源:互联网 发布:mac怎么编辑图片 编辑:程序博客网 时间:2024/04/27 17:28
<script>    function inheritPrototype (subType , superType)    {        var prototype = Object.create(superType.prototype);        prototype.constructor = subType;        subType.prototype = prototype;    }    function SuperType(name)    {        this.name = name;    }    SuperType.prototype.sayName = function(){        alert(this.name);    }    function SubType(name,age)    {        SubType.call(this,name);        this.age = age;    }    inheritPrototype(SubType,SuperType);    SubType.prototype.sayAge = function(){        alert(this.age);    }    </script>

详细解读

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

此函数用于实现继承,其中

var prototype = Object.create(superType.prototype);

用于创建一个新的superType对象并返回给var prototype

 prototype.constructor = subType;

用于改变prototype的默认构造函数

subType.prototype = prototype;

实现subType继承,如果没有上一句,那么构造函数将会是superType的构造函数,所以上一句 prototype.constructor = subType;千万不可以遗漏