JavaScript Reference ยท Statements and Declarations
The class declaration
Reference for the JavaScript class declaration: constructors, methods, fields, static members, getters, extends and super, and how classes differ from functions.
A class declaration creates a constructor function with a cleaner syntax. It bundles a constructor, methods that live on the prototype, and optionally fields, accessors and static members. Under the hood classes are built on prototypes, but they add stricter rules that prevent common mistakes.
class Point { constructor(x, y) { this.x = x; this.y = y; } }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
class Name extends Parent { field = value; #privateField = value; static staticField = value; constructor(params) { super(args); } method() {} get prop() {} set prop(v) {} static staticMethod() {} static { /* static initialization block */ } }
| Part | Description |
|---|---|
Name |
Binds the class in the enclosing block scope. |
extends Parent |
Optional. The class inherits from Parent; its constructor must call super() before using this. |
constructor |
Optional special method. A class has at most one. |
Usage notes
- Always strict mode. Code inside a class body runs in strict mode.
- Not callable. Calling a class without
newthrows aTypeError. - Not hoisted like functions. The name exists from the top of the block but is in the temporal dead zone until the declaration runs.
- Methods are non-enumerable and shared on
Class.prototype; fields are created on each instance. Arrow-function fields give each instance its own bound function. - Private members begin with
#and are accessible only inside the class body. thisis lost when a method is detached. Passingobj.methodas a callback calls it without its object; usebind()or an arrow-function field.- Class expressions (
const A = class {}) work too, optionally with their own inner name. - Prefer composition over deep inheritance chains.
Browser support
Classes work in all current browsers. Public and private fields, static blocks and private methods are newer additions; every current browser supports them, but check a compatibility table for older targets.