Int*_*aek 0 javascript static-methods this ecmascript-6
class Circle {
constructor() {
this.width = 2;
this.height = 3;
}
static area() {
return this.width * this.height
}
}
console.log(Circle.area()) // NaN
Run Code Online (Sandbox Code Playgroud)
我了解到 Class 的静态方法将 this 绑定到 Class 本身,而不是 Instance 的新对象。所以我期望 Cicle.area() 返回 6,它来自 (2 * 3)。但实际结果返回 NaN。我找不到原因。
您的构造函数绑定到该类的实例。这就是this.height
和 的this.width
存储位置(在类的实例上)。
静态方法绑定到类,并且类本身没有静态height
或属性。width
因此,当您尝试将两个现有undefined
值相乘时,您会得到 NaN。
在这种情况下,如果您想area
成为静态方法,则必须将高度和宽度传递给它,因为它不绑定到任何具有现有height
或 的实例width
。
class Rectangle {
static area(height, width) {
return width * height;
}
}
console.log(Rectangle.area(10, 6));
Run Code Online (Sandbox Code Playgroud)
或者,如果您想使用实例的高度和宽度,那么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
Run Code Online (Sandbox Code Playgroud)
注意:我将示例转换为 Rectangle 类,因为我不确定圆形的高度和宽度意味着什么。