js的继承

本文详细探讨了JavaScript中五种常见的继承实现方式:call()、prototype、call()+prototype、拓展实例以及ES6的class extends。每种方式的优缺点都进行了分析,包括能否传参构造父类、能否获取父类原型上的属性和方法等关键点。通过实例展示了它们在实际应用中的效果,帮助读者深入理解JavaScript的继承机制。
摘要由CSDN通过智能技术生成

1.call()

能够传参构造函数,不能获取parent原型上的属性和方法

function Children(a, b){
    Parent.call(this, a, b);
}
Parent.prototype.c = 'c';
Parent.prototype.getC = function(){};
let children = new Children(a, b);
children.a // a
children.b // b
children.c // undefined
children.getC // 报错 not a Function

2.prototype

能够获取parent原型上的属性和方法,不能传参构造父类的属性值

function Children(c){
    this.c = c;
}
Parent.prototype.c = 'c';
Parent.prototype.getC = function(){};
let children = new Children(c);
children.a // a 不能传值构造
children.b // b 不能传值构造
children.c // c
children.getC // function

3.call() + prototype

能构造父类属性,也能拿到原型上的值,但是会构建2次实例,冗余

function Children(a, b, c){
    Parent.call(this, a, b); // 实例了一次
    this.c = c;
}
Parent.prototype.c = 'c';
Parent.prototype.getC = function(){};
Children.prototype = new Parent(); // 实例了一次
let children = new Children(c);
children.a // a 
children.b // b 
children.c // c
children.getC // function

4.拓展实例

能构造父类属性,也能拿到原型上的值,相当于是拓展了个Parent函数

function Children(a, b, c){
    let obj = new Parent(a, b);
    obj.c = c;
    return obj;
}
Parent.prototype.d = 'd';
Parent.prototype.getD = function(){};
let children = new Children(a, b, c);
children.a // a 
children.b // b 
children.c // c
children.d // d
children.getD // function

5.ES6 class extends

class继承是把父类的this实例出来然后子类继承父类的this,如果没调用super(),则子类没有this

class Children{
    constructor(a, b, c){
        super(a, b); // super后才会有this
        this.c = c;
    }
}
let children = new Children(a, b, c);
children.a // a 
children.b // b 
children.c // c

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值