Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Statements and declarations
  5. class

class

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨March 2017⁩.

Theclass declaration creates abinding of a newclass to a given name.

You can also define classes using theclass expression.

Try it

class Polygon {  constructor(height, width) {    this.area = height * width;  }}console.log(new Polygon(4, 3).area);// Expected output: 12

Syntax

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

Description

The class body of a class declaration is executed instrict mode. Theclass declaration is very similar tolet:

  • class declarations are scoped to blocks as well as functions.
  • class declarations can only be accessed after the place of declaration is reached (seetemporal dead zone). For this reason,class declarations are commonly regarded asnon-hoisted (unlikefunction declarations).
  • class declarations do not create properties onglobalThis when declared at the top level of a script (unlikefunction declarations).
  • class declarations cannot beredeclared by any other declaration in the same scope.

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

js
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 namedRectangle, then extend it to create a class namedFilledRectangle.

Note thatsuper(), used in theconstructor, can only be used in constructors, andmust be calledbefore thethis keyword can be used.

js
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

Specification
ECMAScript® 2026 Language Specification
# sec-class-definitions

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp