0

Say you have class Foo

class Foo {
    constructor(name) {
        this.name = name;
    }
    sayName() {
        console.log('My name is ' + this.name);
    }
}

It's possibly to have instance functions like 'sayName'

  new Foo('Kevin').sayName() // My name is Kevin

but I would like to have a Class Function.

I can do this: ie.

  Foo.sayClassName = () => console.log('My Name is Foo')
  Foo.sayClassName() // 'My Name is Foo'

But I would like to Declare this when declaring the class. Is this possible?

lonewarrior556
  • 3,917
  • 2
  • 26
  • 55

3 Answers3

1

You can use a static method.

class Foo {
    constructor(name) {
        this.name = name;
    }
    sayName() {
        console.log('My name is ' + this.name);
    }
    static sayClassName(){
      console.log('My Name is Foo');
    }
}
Foo.sayClassName();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

Yes, if the member function is static:

class Foo {
  constructor(name) {
    this.name = name;
  }
  static sayName() {
    console.log("sayName() called");
  }
}

Foo.sayName()
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
1

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); } }
0xLogN
  • 3,289
  • 1
  • 14
  • 35