利用原型继承和类继承两种方案分别实现:Shape(图形)、Rectangle(矩形),其中Shape有颜色(color)、类型(type,如三角形或矩形)等属性和toString(返回图形的color、type属性构成的字符串)、getArea(不知道怎么计算面积,空方法)等方法,Rectangle有a(边长a)、b(边长b)属性和toString(返回Shape中的color和两条边构成的字符串)、getArea等方法。
时间: 2024-02-28 22:57:43 浏览: 18
好的,我可以为您提供两种方案实现上述需求:
方案一:原型继承
```javascript
// Shape原型对象
const Shape = {
color: '',
type: '',
toString() {
return `color: ${this.color}, type: ${this.type}`;
},
getArea() {}
};
// Rectangle原型对象
const Rectangle = Object.create(Shape);
Rectangle.a = 0;
Rectangle.b = 0;
Rectangle.toString = function() {
return Shape.toString.call(this) + `, a: ${this.a}, b: ${this.b}`;
};
Rectangle.getArea = function() {
return this.a * this.b;
};
// 测试
const rect = Object.create(Rectangle);
rect.color = 'red';
rect.type = 'rectangle';
rect.a = 3;
rect.b = 4;
console.log(rect.toString()); // color: red, type: rectangle, a: 3, b: 4
console.log(rect.getArea()); // 12
```
方案二:类继承
```javascript
// Shape类
class Shape {
constructor(color, type) {
this.color = color;
this.type = type;
}
toString() {
return `color: ${this.color}, type: ${this.type}`;
}
getArea() {}
}
// Rectangle类
class Rectangle extends Shape {
constructor(color, a, b) {
super(color, 'rectangle');
this.a = a;
this.b = b;
}
toString() {
return super.toString() + `, a: ${this.a}, b: ${this.b}`;
}
getArea() {
return this.a * this.b;
}
}
// 测试
const rect = new Rectangle('red', 3, 4);
console.log(rect.toString()); // color: red, type: rectangle, a: 3, b: 4
console.log(rect.getArea()); // 12
```
以上两种方案都实现了Shape和Rectangle类/原型对象,并且实现了toString和getArea方法。其中方案一使用了原型继承,方案二使用了类继承。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)