利用ES6中的类,实现子类继承父类,其中父类有money、cars和house属性以及manage()方法。
时间: 2023-12-10 09:36:57 浏览: 29
可以这样实现:
```javascript
class Parent {
constructor(money, cars, house) {
this.money = money;
this.cars = cars;
this.house = house;
}
manage() {
console.log("Managing...");
}
}
class Child extends Parent {
constructor(money, cars, house, toys) {
super(money, cars, house);
this.toys = toys;
}
play() {
console.log("Playing...");
}
}
const parent = new Parent(1000000, 3, "Villa");
parent.manage(); // "Managing..."
const child = new Child(10000, 1, "Apartment", 50);
console.log(child.money); // 10000
console.log(child.toys); // 50
child.manage(); // "Managing..."
child.play(); // "Playing..."
```
在子类中,我们通过 `extends` 关键字来继承了父类的属性和方法。同时,我们还可以在子类中添加新的属性和方法,比如上面的 `toys` 属性和 `play()` 方法。在子类的构造函数中,我们通过 `super()` 调用了父类的构造函数,来初始化从父类继承下来的属性。