what is static in 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: 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));