【发布时间】:2021-11-08 01:23:19
【问题描述】:
class Circle {
constructor() {
this.width = 2;
this.height = 3;
}
static area() {
return this.width * this.height
}
}
console.log(Circle.area()) // NaN
我了解到 Class 的静态方法将 this 绑定到 Class 本身,而不是 Instance 的新对象。 所以我预计 Cicle.area() 会返回 6,它来自 (2 * 3)。但实际结果返回 NaN。我找不到原因。
【问题讨论】:
-
“为什么返回 NaN?”...因为
undefined * undefined是NaN -
请edit 解释您期望的结果是什么以及为什么。
-
"我了解到 Class 的静态方法绑定到 Class 本身,而不是 Instance 的新对象。" - 所以你知道
Circle.width和 @987654326 @ 是undefined,因为Circle是类而不是new Circle()实例?
标签: javascript ecmascript-6 this static-methods