js实现继承的几种方式

  1. 原型链继承
    // 原型链的继承
    function Person() {
        this.hobby = {
            sing: '小星星'
        }
    }
    
    function Man() {
    
    }
    Man.prototype = new Person()
    Man.prototype.constructor = Man
    
    const  man1= new Man()
    const man2 = new Man()
    man2.hobby.sing = '两只老虎'
    console.log(man1.hobby.sing);//两只老虎
    console.log(man2.hobby.sing);//两只老虎
    // 缺点:
    // 1、父类属性赋值给子类的原型属性,此时父类属性属于共享属性
    // 2、子类实例化时无法向父类传参
    
    //解决办法:构造函数继承
  2. 构造函数继承

    // 构造函数继承
    function Person() {
        this.hobby = {
            sing: '小星星'
        }
    }
    
    function Man(arg) {
        Person.call(this, arg)
    }
    
    const man1 = new Man()
    const man2 = new Man()
    man2.hobby.sing='两只老虎'
    console.log(man1.hobby.sing);
    console.log(man2.hobby.sing);
    
    //缺点:原型链上的方法无法被继承
    
    //解决办法:组合式继承
  3. 组合式继承

    // 组合式继承
    function Person() {
        this.hobby = {
            sing: '小星星'
        }
    }
    
    function Man(arg) {
        Person.call(this, arg)
    }
    
    Man.prototype = new Person()
    Man.prototype.constructor = Man
    
    const man1 = new Man()
    const man2 = new Man()
    man2.hobby.sing='两只老虎'
    console.log(man1.hobby.sing);
    console.log(man2.hobby.sing);
    //缺点:会调用两次父类的构造函数
    //解决办法:寄生组合式继承
  4. 寄生组合继承

    //寄生组合式继承
    function Person() {
        this.hobby = {
            sing: '小星星'
        }
    }
    
    function Man(arg) {
        Person.call(this, arg)
    }
    
    Man.prototype = Object.creat(Person.prototype)
    Man.prototype.constructor = Man
    
    const man1 = new Man()
    const man2 = new Man()
    man2.hobby.sing='两只老虎'
    console.log(man1.hobby.sing);
    console.log(man2.hobby.sing);
  5. 多重继承

    // 多重继承
    function Person() {
        this.hobby = {
            sing: '小星星'
        }
    }
    
    function Father() {
        this.sex = '男'
    }
    
    function Child(arg) {
        Person.call(this, arg)
        Father.call(this, arg)
    }
    Child.prototype = Object.create(Person.prototype)
    Object.assign(Child.prototype, Father.prototype)
    Child.prototype.constructor=Child
    
    const child1 = new Child()
    const child2 = new Child()
    child2.hobby.sing='两只老虎'
    console.log(child1.hobby.sing);
    console.log(child2.hobby.sing);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值