javascript - 下例中子类是否继承了父类原型(JS)
问题描述
以下代码:
class Rectangle {
constructor(w, h) {
this.w = w;
this.h = h;
}
}
Rectangle.prototype.area = function () {
return (this.w * this.h);
};
class Square extends Rectangle {
constructor(w, h) {
super(w, h);
// this.w = w;
// this.h = h;
}
}
我的继承有问题吗?
我正在尝试使用:
const rec = new Rectangle(3, 4);
const sqr = new Square(3);
console.log(rec.area());
console.log(sqr.area());
rec
打印正确的答案,但sqr
打印出来:NaN
我也尝试过添加一个 Square 原型:
Square.prototype.area = function () {
return (this.w * this.w);
};
但输出是:
-1
-1
所以这也影响了地区rec.area()
解决方案
由于Square
将仅使用一个参数调用构造函数(因为它的大小在所有方面都相等),因此您需要将其“转换”为Rectangle
需要 2 个参数(宽度和高度)的构造函数调用。由于正方形都相等,因此您需要将该单个参数两次传递给Rectangle
构造函数:
class Rectangle {
constructor(w, h) {
this.w = w;
this.h = h;
}
area() { // Use this notation for prototype methods
return this.w * this.h;
}
};
class Square extends Rectangle {
constructor(w) { // One argument...
super(w, w); // ...Two arguments, but width == height
}
}
let square = new Square(10);
console.log(square.area());
推荐阅读
- javascript - 弹出从视频容器中流出
- python - 我如何获得第二个表类?
- java - toString 方法打印出带有 2D 布尔数组的游戏板
- parameters - 当我使用参数时,SqlDataAdapter.Fill 永远不会结束
- spring - 将spring batch与kafka集成的最新(2019)首选方式是什么?
- java - Caffeine LoadingCache 实现的单元测试单独通过,但一起运行时失败
- javascript - 为什么我不能在使用当前时间的 if/else 语句旁边打印当前时间?
- c# - 使用 vb6 dll。你调用的对象是空的。它适用于开发,但在部署 asp.net 时失败
- r - R:将指标列映射到构成列的内容
- python - 计算包含特定参数的数据框列中的值