如何停止共享方法与类和扩展?
我正在创建两个类,矩形
和square
,基于 mdn 。
由于矩形是正方形的原型,因此它们共享相同的方法区域()
。
但是,我希望afear()
仅在length ===高度
时才能运行。
我尝试在super()之后添加一个if-statement,但是IT区域()仍然返回this.length* this.height,无论错误输入如何。
我可以在Area()
方法中添加if-statement
,但我之所以没有,是因为当我们计算矩形的面积时,这是没有意义的。
class Rectangle {
constructor(length, height){
this.length = length;
this.height = height;
}
area(){
return this.length*this.height;
}
}
class Square extends Rectangle {
constructor(length, height){ // have area() return "Not a square" instead of a number
super(length, height);
if (length !== height) {
console.log("Not a square.")
}
this.name = "square";
}
}
const rectangle = new Rectangle(2,3);
console.log(rectangle.area());
const square = new Square(5,2);
console.log(square.area())
I am creating two classes, Rectangle
and Square
, based on the example shown on MDN.
Since Rectangle is the prototype of Square, they share the same method area()
.
However, I want area()
to run only if length === height
for the square.
I've tried to add an if-statement after super(), but it area() still returns this.length* this.height regardless of an erroneous input.
I could add an if-statement
in the area()
method, but I did not because it would not make sense when we are calculating the area of a rectangle.
class Rectangle {
constructor(length, height){
this.length = length;
this.height = height;
}
area(){
return this.length*this.height;
}
}
class Square extends Rectangle {
constructor(length, height){ // have area() return "Not a square" instead of a number
super(length, height);
if (length !== height) {
console.log("Not a square.")
}
this.name = "square";
}
}
const rectangle = new Rectangle(2,3);
console.log(rectangle.area());
const square = new Square(5,2);
console.log(square.area())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当条件不匹配时,您可以丢弃错误。这将停止对物体的构造。
但是,
在这种情况下,我认为仅接受1个参数以防止此错误的情况更加有效:
You can throw an error when the criteria is not matched. This will stop the construction of the object.
However
in this case i think it makes more sence to only accept 1 parameter to prevent this error from happening: