// 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));
class Triple {
static customName = 'Tripler';
static description = 'I triple any number you provide';
static calculate(n = 1) {
return n * 3;
}
}
class SquaredTriple extends Triple {
static longDescription;
static description = 'I square the triple of any number you provide';
static calculate(n) {
return super.calculate(n) * super.calculate(n);
}
}
console.log(Triple.description); // 'I triple any number you provide'
console.log(Triple.calculate()); // 3
console.log(Triple.calculate(6)); // 18
const tp = new Triple();
console.log(SquaredTriple.calculate(3)); // 81 (not affected by parent's instantiation)
console.log(SquaredTriple.description); // 'I square the triple of any number you provide'
console.log(SquaredTriple.longDescription); // undefined
console.log(SquaredTriple.customName); // 'Tripler'
// This throws because calculate() is a static member, not an instance member.
console.log(tp.calculate()); // 'tp.calculate is not a function'
/*
* When using function constructors, you can create
* a static property by simply using dot notation
* on the constructor function.
*/
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.dist = function(p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
};
Point.dist(new Point(0, 0), new Point(1, 0));
/*
* When using classes, you can create a static
* property using the static keyword.
*/
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static dist(p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
}
Point.dist(new Point(0, 0), new Point(1, 0));