Static Methods
Static methods are methods directly on the class object (the parent of prototype) and will allow for this behavior. To do this, prefix the method with 'static'. MDN: Classes/static
The static
keyword defines a static method or property for a class. Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself.
Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.
class Foo {
constructor() {}
static bar() { console.log('called'); }
}
Foo.bar(); // prints 'called'
Replicating the behavior
JS classes are just objects with a prototype. For example:
// class Foo {
// constructor(name) { console.log('Defined: ' + name); this.name = name; }
// static staticFunc() { console.log('[static]'); }
// method() { console.log(this.name); }
// }
let Foo = function(name) { console.log('Defined: ' + name); this.name = name; }
Foo.staticFunc = function() { console.log('[static]'); }
Foo.prototype = { method: function() { console.log(this.name); } }