提问人:Intaek 提问时间:11/8/2021 最后编辑:Intaek 更新时间:11/8/2021 访问量:732
如果 ES6 的类静态方法的 this 绑定到类,为什么会返回 NaN?
If ES6's class static method's this binds to the class, why does this return NaN?
问:
class Circle {
constructor() {
this.width = 2;
this.height = 3;
}
static area() {
return this.width * this.height
}
}
console.log(Circle.area()) // NaN
我了解到 Class 的静态方法将此绑定绑定到 Class 本身,而不是 Instance 的新对象。 所以我预计 Cicle.area() 返回 6,即来自 (2 * 3)。但实际结果返回 NaN。我找不到原因。
答:
6赞
jfriend00
11/8/2021
#1
构造函数绑定到类的实例。这是存储的位置(在类的实例上)。this.height
this.width
静态方法绑定到类,类本身没有静态或属性。因此,当您尝试将两个现有值相乘时,您将得到 NaN。height
width
undefined
在这种情况下,如果要成为静态方法,则必须将高度和宽度传递给它,因为它未绑定到具有现有 或 .area
height
width
class Rectangle {
static area(height, width) {
return width * height;
}
}
console.log(Rectangle.area(10, 6));
或者,如果要使用实例的高度和宽度,则需要是实例方法,而不是静态方法。area
class Rectangle {
constructor(height, width) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
let rect = new Rectangle(10, 6);
console.log(rect.area()) // 60
注意:我将示例转换为 Rectangle 类,因为我不确定圆形的高度和宽度是什么意思。
评论
undefined * undefined
NaN
Circle.width
Circle.height
undefined
Circle
new Circle()