【小白鲨笔记】js面试题(十一)

18 篇文章 0 订阅

十一、Js继承

ES6

  • 采用extends关键词对父类的继承

    ❗注意:一定要在子类构造器第一行加入super父类构造器的调用

    class Parent {
        constructor(){ this.age = 10 }
    }
    class Child extends Parent {
        constructor(){ 
            super() //若继承则必须加上super -- 否则报错
            this.name = 'jaws'
        }
    }
    console.log(new Child().age) //若没有继承extends则视为undefined
    

原型链

  • 将原型指向父类即可

    function Parent { this.age = 10 }
    function Child { this.name = 'jaws' }
    Child.prototype = new Parent()
    console.log(new Child().age) //10
    

借用构造函数

  • 利用call方法改变this指向:无法实现共享

    function Parent { this.age = 10 }
    function Child {
        this.name = 'jaws'
        Parent.call(this)
    }
    console.log(new Child().age) //10
    

组合式

  • 可以实现共享、又可以解决原型链的继承的问题

    function Parent { this.age = 10 }
    function Child {
        // 2.将this指向父类
        Parent.call(this)
        this.name = 'jaws'
    }
    // 1. 将原型链串联起来
    Child.prototype = new Parent()
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值