JS: static (keyword)

By Xah Lee. Date: . Last updated: .

Class method names can be declared with a static keyword in front. This is called static method.

Static methods becomes a property of the class function itself.

Static method does not become part of the prototype object. Thus, object created by the class does not inherit static methods.

// demo behavior of the keyword “static”

class Kas {
 static ss(x) {
  return x + 1;
 }
}

// static methods are properties of the class function itself
console.assert(Object.hasOwn(Kas, "ss"));

// call the method
console.assert(Kas.ss(3) === 4);

Static method of a class cannot be called from a object created by the class. (because static method isn't in the prototype object. Static method are property of the class itself. )

class Xeee {
 static ss(x) {
  return x + 1;
 }
}

console.assert(Object.hasOwn(Xeee.prototype, "ss") === false);

const jj = new Xeee();

// static method cannot be called from a instance of the class
try {
 jj.ss(4);
} catch (xerror) {
 console.log(xerror);
 // TypeError: jj.ss is not a function
}

JavaScript. Constructor, Class