JS: Keyword “static” (static method)

By Xah Lee. Date: .

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 will not inherit static methods.

// demo behavior of the keyword “static”

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

// static methods are properties of the class function itself
console.log(Dd.hasOwnProperty("ss"));

// call the method
console.log(Dd.ss(3) === 4);

Static method cannot be called from a instance of the object. (because static method isn't in the prototype object.)

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

console.log(Ee.prototype.hasOwnProperty("ss") === false);

const jj = new Ee();

// static method cannot be called from a instance of the object
console.log(
  jj.ss(4),
);
// error: Uncaught TypeError: jj.ss is not a function

JavaScript, Constructor, Class