call static method in class javascript code example
Example 1: js class static function
class myClass{
constructor(){
this.myLocaleVariable=1;
}
localfunction(){
return "im local unique to this variable";
}
static publicfunction(){
return "i can be called without an obj"
}
}
myClass.myPublicVariable = 0;
myClass.localfunction();
myClass.publicfunction();
myClass.myLocaleVariable;
myClass.myPublicVariable;
var obj = new myClass;
obj.localfunction();
obj.publicfunction();
obj.myLocaleVariable;
obj.myPublicVariable;
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());
})