android-logo

JavaScript Static Method


Static methods are associated with a class, not with its instances. They are assigned by the static keyword in a class. Before ES6, you had to add a static method directly to the class constructor to declare it. We may also add a method to the class function itself, rather than the prototype of the class function.


Example


class Dog {

    static bark() {
      return "howl";
    }
  }
  
console.log(Dog.bark())  // howl

Static properties are similar to standard class properties, except they are preceded by the word static.


Lets take another example


class Animal {
    constructor(sound) {
      this.sound = sound;
    }
    static bark(v) {
      return "Dogs " + v.sound;
    }
  }
  
let play = new Animal("howl");
console.log(Animal.bark(play));

Output

Dogs howl


previous-button
next-button

facebook-logo
twitter-logo
instagram-logo

2020 © All rights reserved.