【问题标题】:If ES6's class static method's this binds to the class, why does this return NaN?如果 ES6 的类静态方法 this 绑定到类,为什么 this 返回 NaN?
【发布时间】: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 * undefinedNaN
  • edit 解释您期望的结果是什么以及为什么。
  • "我了解到 Class 的静态方法绑定到 Class 本身,而不是 Instance 的新对象。" - 所以你知道 Circle.width 和 @987654326 @ 是 undefined,因为 Circle 是类而不是 new Circle() 实例?

标签: javascript ecmascript-6 this static-methods


【解决方案1】:

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

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

在这种情况下,如果您希望 area 成为静态方法,则必须将高度和宽度传递给它,因为它未绑定到具有现有 heightwidth 的任何实例。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多