JavaScript如何实现继承的几种方法

<script>
    //1.借助构造函数继承
    function parent() {
        this.name = "parent"
    }
    parent.prototype.say = 'say'
    function child() {
        parent.call(this);
        this.type = 'child'
    }
    // console.log(new child)
    //缺点:不会继承原型链上的属性。

    //2.通过原型链来继承
    function parent1() {
        this.name = "parent1"
        this.arr = [1, 2]
    }
    function child1() {
        this.type = 'child1'
    }
    child1.prototype = new parent1();
    var s1 = new child1()
    var s2 = new child1()
    s1.arr.push(3)
    //console.log(s1)
    //console.log(s2)
    //缺点:修改父类的属性值,会改变所有子类中继承的值,原型链中的原型对象是共用的。

    //3.组合继承
    function parent2() {
        this.name = "parent2"
    }
    function child2() {
        parent2.call(this);
        this.type = 'child2'
    }
    child2.prototype=new parent2();
    //console.log(new child2)
    //缺点:父级构造函数执行了的两次

    //3.1组合继承的优化
    function parent3() {
        this.name = "parent3"
    }
    function child3() {
        parent3.call(this);
        this.type = 'child3'
    }
    child3.prototype=parent3.prototype;
    //console.log(new child3)
    //缺点:无法判断对象是由谁直接实例化的 

    //3.2组合继承的优化
    function parent4() {
        this.name = "parent4"
    }
    function child4() {
        parent4.call(this);
        this.type = 'child4'
    }
    child4.prototype=Object.create(parent4.prototype)//隔离构造函数
    child4.prototype.constructor=child4;//重新赋值构造函数

    //4.es6 class与extends来实现继承
    class parent5{
        constructor(name){
            this.name=name
        }
    }
    class children5 extends parent5{
        constructor(name,type){
            super(name)
            this.type=type
        }
    }
    console.log(new children5('1','2'))

</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值