static keyword js code example
Example 1: js class static function
class myClass{
constructor(){
this.myLocaleVariable=1;//this.varname in the constructer function makes a locale var
}
localfunction(){
return "im local unique to this variable";
}
static publicfunction(){
return "i can be called without an obj"
}
}
myClass.myPublicVariable = 0;
myClass.localfunction();//error
myClass.publicfunction();//"i can be called without an obj"
myClass.myLocaleVariable;//error
myClass.myPublicVariable;//0
var obj = new myClass;
obj.localfunction();//"im local unique to this variable"
obj.publicfunction();//error
obj.myLocaleVariable;//1
obj.myPublicVariable;//error
Example 2: static js
// the static method is a method which cannot be called through a class instance.
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
// *** JS Class STATIC method ***
class Animal {
sayHello() {
return `${this.constructor.greeting}! I'm ${this.name}!`;
}
}
class Cat extends Animal {
constructor(name) {
super(); // connects parent to child/constructor
this.name = name; //=> need this line otherwise name undefined
}
static greeting = 'Feed me';
}
class Dog extends Animal {
constructor(name) {
super();
this.name = name; // same output type as above
}
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());
})
// output = Feed me! I'm Garfield! Sigh! I'm Snoopy!
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))
// => [ 'length', 'prototype', 'my_static_method', 'name' ]