When to use static methods JavaScript code example
Example 1: js static methods
class Foo(){ static methodName(){ console.log("bar") }}
Example 2: javascript class static method
class Animal {
sayHello() {
return `${this.constructor.greeting}! I'm ${this.name}!`;
}
}
class Cat extends Animal {
constructor(name) {
super();
this.name = name;
}
static greeting = 'Feed me';
}
class Dog extends Animal {
constructor(name) {
super();
this.name = name;
}
static greeting = 'Sigh';
}
const run = document.getElementById("run");
run.addEventListener('click', () => {
let Garfield = new Cat('Garfield');
let Snoopy = new Dog('Snoopy');
console.log(Garfield.sayHello());
console.log(Snoopy.sayHello());
})
Example 3: get static methods of class javascript
class Hi {
constructor() {
console.log("hi");
}
my_method(){}
static my_static_method() {}
}
function getStaticMethods(cl) {
return Object.getOwnPropertyNames(cl)
}
console.log(getStaticMethods(Hi))