static keyword js 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: static js
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
const p1 = new Point(7, 2);
const p2 = new Point(3, 8);
console.log(Point.distance(p1, p2));
Example 3: 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 4: 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))