class类的继承

在这里插入代码片## class类的继承
1.Class 可以通过 extends 关键字实现继承

class Point {
    
}

class ColorPoint extends Point {
}

上面代码定义了一个ColorPoint类,该类通过extends关键字,继承了Point类的所有属性和方法。

super关键字,表示父类的构造函数,用来新建父类的this对象。

class fruit {
    constructor(price, weight) {
        this.price = price;
        this.weight = weight
    }
    total(cont) {
        return cont * this.price * this.weight;
    }
}
class apple extends fruit {
    constructor(price, weight) {
        super(price, weight) //父类的构造函数
    }
    total(cont) {
        return super.total(cont)//父类的tatal方法
    }
}

子类必须在constructor方法中调用super方法,否则新建实例时会报错

class Point { /* ... */ }

class ColorPoint extends Point {
  constructor() {
  }
}

let cp = new ColorPoint(); // ReferenceError
案例:求各种水果的价钱


class fruit {
    constructor(price, weight) {
        this.price = price;
        this.weight = weight;

    }
    total() {
        return this.price * this.weight;
    }
}
class Apple extends fruit {
    constructor(price, weight) {
        super(price, weight) //
    }
}
class Banner extends fruit {
    constructor(price, weight) {
        super(price, weight)
    }
}
class Bear extends fruit {
    constructor(price, weight) {
        super(price, weight)
    }
}
const app = new Apple(10, 10);
const banner = new Banner(10, 10);
const bear = new Bear(10, 10);
console.log(app.total() + banner.total() + bear.total());

总结: 1.Class 可以通过extends关键字实现继承

2.它在这里表示父类的构造函数,用来新建父类的this对象。

3.子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象。

4.ColorPoint继承了父类Point,但是它的构造函数没有调用super方法,导致新建实例时报错。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值