如果 ES6 的类静态方法的 this 绑定到类,为什么会返回 NaN?

If ES6's class static method's this binds to the class, why does this return NaN?

提问人:Intaek 提问时间:11/8/2021 最后编辑:Intaek 更新时间:11/8/2021 访问量:732

问:

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。我找不到原因。

javascript ecmascript-6 这个 静态方法

评论

1赞 Phil 11/8/2021
“为什么这返回NaN?”...因为是undefined * undefinedNaN
0赞 Sebastian Simon 11/8/2021
编辑并解释您期望的结果是什么以及原因。
1赞 Bergi 11/8/2021
"我了解到 Class 的静态方法与 Class 本身绑定,而不是 Instance 的新对象。- 所以你知道 和 是 ,因为是类而不是实例吗?Circle.widthCircle.heightundefinedCirclenew Circle()

答:

6赞 jfriend00 11/8/2021 #1

构造函数绑定到类的实例。这是存储的位置(在类的实例上)。this.heightthis.width

静态方法绑定到类,类本身没有静态或属性。因此,当您尝试将两个现有值相乘时,您将得到 NaN。heightwidthundefined

在这种情况下,如果要成为静态方法,则必须将高度和宽度传递给它,因为它未绑定到具有现有 或 .areaheightwidth

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 类,因为我不确定圆形的高度和宽度是什么意思。