This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

  • 12.3 JS Class Static

    • Static class methods are defined on the class itself.
    • You cannot call a static method on an object, only on an object class.
    Example 1: JS Class Static Methods part 1
    class Car {
      constructor(name) {
        this.name = name;
      }
      static hello() {
        return "Hello!!";
      }
    }
    
    let myCar = new Car("Ford");
    
    // You can call 'hello()' on the Car Class:
    document.getElementById("demo").innerHTML = Car.hello();
    
    // But NOT on a Car Object:
    // document.getElementById("demo").innerHTML = myCar.hello();
    // this will raise an error.

    If you want to use the myCar object inside the static method, you can send it as a parameter:

    Example 2: JS Class Static Methods part 2
    class Car {
      constructor(name) {
        this.name = name;
      }
      static hello(x) {
        return "Hello " + x.name;
      }
    }
    let myCar = new Car("Ford");
    document.getElementById("demo").innerHTML = Car.hello(myCar);
    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon