static 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: js class static
class ClassWithStaticMethod {
static staticMethod() {
return 'static method has been called.';
}
}
console.log(ClassWithStaticMethod.staticMethod());
Example 3: 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 4: js static methods
class Foo(){ static methodName(){ console.log("bar") }}