JS: Class Syntax

By Xah Lee. Date: . Last updated: .

Class Declaration Syntax

The syntax for class declaration is:

class ClassName { method1 method2 method3 }

where a method has one of the following form, all are optional:

constructor (param) {body}
  • This defines the Constructor function.
  • This function is automatically called when new ClassName is called.
  • There can only be one constructor. If not given, by default it is constructor () {}, which does nothing.
static name (param) {body}
This is called static method. [see Keyword “static” (static method)]
name (param) {body}
This is called prototype method.
get name () {body}
This is called getter method. Also part of the prototype methods. [see Getter Setter Properties]
set name (param) {body}
This is called setter method. Also part of the prototype methods. [see Getter Setter Properties]

(Note: class body must all be function definitions.)

Example:

// example of a class
class Cc {
  constructor(x) {
    this.p = x;
    console.log("constructor called with arg " + x);
  }

  mm(x) {
    console.log("mm called with arg " + x);
  }

  set p1(x) {
    console.log("setter called");
  }

  get p1() {
    console.log("getter called");
  }

  static ss(x) {
    console.log("ss called with arg " + x);
  }
}

// ---------------------------
// using the class

// static method is called directly, not via instance of a object
Cc.ss(3); // prints: ss called with arg 3

// create a instance
const xx = new Cc(4); // prints: constructor called with arg 4

console.log(xx); // Cc { p: 4 }

xx.mm(2); // prints: mm called with arg 2

xx.p1 = 1; // prints: "setter called"

xx.p1; // prints: "getter called"

JavaScript, Constructor, Class

BUY ΣJS JavaScript in Depth