利用ES6中的类,实现子类继承父类,其中父类有money、cars和house属性以及manage()方法。
时间: 2023-12-10 21:36:56 浏览: 29
以下是一个简单的实现示例:
```
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...");
}
}
```
在这个示例中,我们定义了一个 `Parent` 类,它有 `money`、`cars` 和 `house` 属性以及一个 `manage()` 方法。然后,我们定义了一个 `Child` 类,它从 `Parent` 类继承了属性和方法,并添加了一个 `toys` 属性和一个 `play()` 方法。
通过使用 `super()` 方法,在 `Child` 类的构造函数中调用 `Parent` 类的构造函数,并且传递相应的参数。
现在,我们可以创建一个 `Child` 对象,并访问其继承来自 `Parent` 类的属性和方法,以及它自己的属性和方法。
```
const child = new Child(1000000, 3, "villa", ["doll", "car"]);
console.log(child.money); // 1000000
child.manage(); // Managing...
console.log(child.toys); // ["doll", "car"]
child.play(); // Playing...
```