docs.rodeo

MDN Web Docs mirror

class

{{jsSidebar("Statements")}} 

The class declaration creates a {{Glossary("binding")}}  of a new class to a given name.

You can also define classes using the class expression.

{{InteractiveExample("JavaScript Demo: Statement - Class")}} 

class Polygon {
  constructor(height, width) {
    this.area = height * width;
  }
}

console.log(new Polygon(4, 3).area);
// Expected output: 12

Syntax

class name {
  // class body
}
class name extends otherName {
  // class body
}

Description

The class body of a class declaration is executed in strict mode. The class declaration is very similar to {{jsxref("Statements/let", "let")}} :

Outside the class body, class declarations can be re-assigned like let, but you should avoid doing so. Within the class body, the binding is constant like const.

class Foo {
  static {
    Foo = 1; // TypeError: Assignment to constant variable.
  }
}

class Foo2 {
  bar = (Foo2 = 1); // TypeError: Assignment to constant variable.
}

class Foo3 {}
Foo3 = 1;
console.log(Foo3); // 1

Examples

A class declaration

In the following example, we first define a class named Rectangle, then extend it to create a class named FilledRectangle.

Note that super(), used in the constructor, can only be used in constructors, and must be called before the this keyword can be used.

class Rectangle {
  constructor(height, width) {
    this.name = "Rectangle";
    this.height = height;
    this.width = width;
  }
}

class FilledRectangle extends Rectangle {
  constructor(height, width, color) {
    super(height, width);
    this.name = "Filled rectangle";
    this.color = color;
  }
}

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN