Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I learned that the static method of Class has this bind to the Class itself, not the Instance’s new object.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading