2021-10-14 js 原型链继承

原型链继承的问题在于 如果构造函数属性有引用对象 实例会公用同一个引用对象

    为避免公用引用对象 就有了 盗用构造函数的继承方式

    function Per(name) {

        Person.call(this, name)

    }

    这种继承方式不但可以解决继承时实例公用同一个引用对象  还能实现子实例向父构造函数传参

    但是盗用构造函数的问题在于  不能继承父构造函数在prototype方法

    组合继承就解决了盗用构造函数继承的问题

    function Man(name) {

        this.name = name

    }

    Man.prototype.getName = function(){

        return this.name

    }

    function SuperMan(name, isCanFly) {

        Man.call(this, name)

        this.isSuperMan = isCanFly

    }

    SuperMan.prototype = new Man()

    SuperMan.prototype.getIsSuperMan = function() {

        return this.isSuperMan

    }

    let m = new SuperMan('pp', true)

    console.log(m.getName)

    console.log(m.getIsSuperMan)

    console.log(m.isSuperMan)

    组合继承加强版:寄生组合继承核心:

    function object(o) {

        function F(){}

        F.prototype = 0

        return new F()

    }

    inheritPrototype(supType, superType) {

        let prototype = object(superType.prototype)

        prototype.constructor = supType

        supType.prototype = prototype

    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容