1// Classes : static methods in javascript classes
2
3class Square {
4 constructor(width){
5 this.width = width ;
6 this.height = width ;
7 }
8
9 static equals(a , b){
10 return a.width * a.height === b.width * b.height ;
11 }
12
13 static validDimensions(width , height ){
14 return width === height ;
15 }
16}
17
18console.log(Square.validDimensions(8 , 8));
19console.log(Square.validDimensions(10 , 12));
20console.log(Square.validDimensions(0 ,0 ));
21console.log(Square.validDimensions(2 , 3));
22console.log(Square.validDimensions(-3 , -3));
1class Hi {
2 constructor() {
3 console.log("hi");
4 }
5 my_method(){}
6 static my_static_method() {}
7}
8
9function getStaticMethods(cl) {
10 return Object.getOwnPropertyNames(cl)
11}
12
13console.log(getStaticMethods(Hi))
14// => [ 'length', 'prototype', 'my_static_method', 'name' ]
15
1// *** JS Class STATIC method ***
2
3class Animal {
4 sayHello() {
5 return `${this.constructor.greeting}! I'm ${this.name}!`;
6 }
7 }
8
9 class Cat extends Animal {
10 constructor(name) {
11 super(); // connects parent to child/constructor
12 this.name = name; //=> need this line otherwise name undefined
13 }
14 static greeting = 'Feed me';
15 }
16
17 class Dog extends Animal {
18 constructor(name) {
19 super();
20 this.name = name; // same output type as above
21 }
22 static greeting = 'Sigh';
23 }
24
25 const run = document.getElementById("run");
26 run.addEventListener('click', () => {
27 let Garfield = new Cat('Garfield');
28 let Snoopy = new Dog('Snoopy');
29 console.log(Garfield.sayHello());
30 console.log(Snoopy.sayHello());
31 })
32// output = Feed me! I'm Garfield! Sigh! I'm Snoopy!
1// javascript static methods on Classes are called via the Class Name not via the class Instances
2class Square {
3 constructor(width){
4 this.width = width ;
5 this.height = width ;
6 }
7
8 static equals(a , b){
9 return a.width * a.height === b.width * b.height ;
10 }
11}
12
13
14const newSquare1 = new Square(10);
15const newSquare2 = new Square(9);
16const newSquare3 = new Square(5);
17const newSquare4 = new Square(5);
18console.log(Square.equals(newSquare1 , newSquare2));
19console.log(Square.equals(newSquare3 , newSquare4));