Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

class expression

BaselineWidely available

Theclass keyword can be used to define a class inside an expression.

You can also define classes using theclass declaration.

Try it

const Rectangle = class {  constructor(height, width) {    this.height = height;    this.width = width;  }  area() {    return this.height * this.width;  }};console.log(new Rectangle(5, 8).area());// Expected output: 40

Syntax

js
class {  // class body}class name {  // class body}

Note:Anexpression statement cannot begin with the keywordclass to avoid ambiguity with aclass declaration. Theclass keyword only begins an expression when it appears in a context that cannot accept statements.

Description

Aclass expression is very similar to, and has almost the same syntax as, aclass declaration. As withclass declarations, the body of aclass expression is executed instrict mode. The main difference between aclass expression and aclass declaration is theclass name, which can be omitted inclass expressions to createanonymous classes. Class expressions allow you to redefine classes, while redeclaring a class usingclass declarations throws aSyntaxError. See also the chapter aboutclasses for more information.

Examples

A basic class expression

This is just an anonymous class expression which you can refer to using the variableFoo.

js
const Foo = class {  constructor() {}  bar() {    return "Hello World!";  }};const instance = new Foo();instance.bar(); // "Hello World!"Foo.name; // "Foo"

Named class expressions

If you want to refer to the current class inside the class body, you can create anamed class expression. The name is only visible within the scope of the class expression itself.

js
const Foo = class NamedFoo {  constructor() {}  whoIsThere() {    return NamedFoo.name;  }};const bar = new Foo();bar.whoIsThere(); // "NamedFoo"NamedFoo.name; // ReferenceError: NamedFoo is not definedFoo.name; // "NamedFoo"

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