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 ClassWithInstanceField {
2 instanceField = 'instance field'
3}
4
5class ClassWithStaticField {
6 static staticField = 'static field'
7}
1class myClass{
2
3constructor(){
4this.myLocaleVariable=1;//this.varname in the constructer function makes a locale var
5}
6localfunction(){
7return "im local unique to this variable";
8}
9static publicfunction(){
10return "i can be called without an obj"
11}
12
13}
14myClass.myPublicVariable = 0;
15
16
17
18myClass.localfunction();//error
19myClass.publicfunction();//"i can be called without an obj"
20myClass.myLocaleVariable;//error
21myClass.myPublicVariable;//0
22var obj = new myClass;
23obj.localfunction();//"im local unique to this variable"
24obj.publicfunction();//error
25obj.myLocaleVariable;//1
26obj.myPublicVariable;//error
27
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!
1class ClassWithStaticMethod {
2 static staticMethod() {
3 return 'static method has been called.';
4 }
5}
6
7console.log(ClassWithStaticMethod.staticMethod());
8// expected output: "static method has been called."
9