Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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. So I expected Cicle.area() to return 6, which is from (2 * 3). But the actual outcome returns NaN. I cannot find why.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda