2

How can you make a class's method static (available on the class itself) and accessible from its instances in JavaScript?

class MyClass {
    constructor() {}
    method() {}
}

const myInstance = new MyClass();

myInstance.method(); // calling from instance
MyClass.method(); // calling from class
Mystical
  • 1,805
  • 2
  • 15
  • 31
  • 1
    Possible duplicate of [Call static methods from regular ES6 class methods](https://stackoverflow.com/questions/28627908/call-static-methods-from-regular-es6-class-methods) – Robert Moskal Dec 09 '17 at 04:06
  • A static method is not supposed to be called from an instance by definition... – leaf Dec 09 '17 at 04:24

2 Answers2

2

You can use the static keyword to do so.

class A {
    constructor(){}
    static method(){}
}

const x = new A();

EDIT:

x.constructor.method(); // this is possible
A.method();

In Javascript, static methods are bound to class and not instances, so they can only be called by atleast using the constructor. A.prototype handles instance methods whereas the function A handles it's attributes.

nkprince007
  • 124
  • 9
  • 1
    But that won't work when trying to call it from the instance: *'Uncaught TypeError: x.method is not a function'* – Mystical Dec 09 '17 at 04:10
1

Static method calls are made directly on the class and are not callable on instances of the class. But you can achieve the calls for static members from inside an instance.

Using syntax:

this.constructor.staticfunctionName();

ES6 Class Example:

class MyClass {
    constructor() {}
    static staticMethod() {
        console.log('Static Method');
    }
}
MyClass.staticVar = 777;

var myInstance = new MyClass();
// calling from instance
myInstance.constructor.staticMethod();
console.log('From Inside Class : ',myInstance.constructor.staticVar);

// calling from class
MyClass.staticMethod();
console.log('Class : ', MyClass.staticVar);

For ES5 Function Classes refer to my answer.

Yash
  • 7,342
  • 2
  • 55
  • 63