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

Time:11-08

class Circle {
    constructor() {
        this.width = 2;
        this.height = 3;
    }
    
    static area() {
        return this.width * this.height
    }
} 

console.log(Circle.area()) // NaN

I learned that the static method of Class has this bind to the Class itself, not the Instance's new object. So I expected Cicle.area() to return 6, which is from (2 * 3). But the actual outcome returns NaN. I cannot find why.

CodePudding user response:

Your constructor binds to an instance of the class. That's where this.height and this.width are stored (on an instance of the class).

Static methods bind to the class and there is no static height or width property on the class itself. Thus, you get NaN when you try to multiply two existing undefined values.

In this case, if you want area to be a static method, you would have to pass the height and width to it since it is not bound to any instance that has an existing height or width.

class Rectangle {
    static area(height, width) {
        return width * height;
    }
} 

console.log(Rectangle.area(10, 6));

Or, if you want to use the instance height and width, then area needs to be an instance method, not a static method.

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

Note: I converted the example to a Rectangle class because I'm not sure what height and width mean for a circle.

  • Related