DEV Community

loading...
Cover image for static in JavaScript

static in JavaScript

rahxuls profile image Rahul ・1 min read

This keyword static allows us to create methods and properties that are assigned to the class itself, and not it's instances.

class person {
    // A static method
    statis hello() {
        console.log("Hello!");
    }
}

// Call the static method directly
Person.hello();
Enter fullscreen mode Exit fullscreen mode

Value of "THIS"

Inside statis methods, "this" hold a reference to the class.

class Test {
    statis getThisValue() {
         console.log(thos);
    }
}

// Call the static method
Test.getThisVkaue();

/* 
  class Test { ... }
*/ 
Enter fullscreen mode Exit fullscreen mode

EXAMPLE 1

class Car {
    constructor(make, model) {
         this.make = make; 
         this.make = model; 
    }
    // This statis method creates a new instance of Car
    static createCar(make, mmodel) {
        console.log("Building a new car...");

        return new this(make, model);
    }

    info() {
        console.log(`I'm a ${this.make} ${this.model})
    }
}

// Call the static method "createCar" directly from the car class

let bmw = Car.createCar("BMW", "E82");

// Run our "info" method from the Car instance

bmw.info();

/*
   Building a new car...

   I'm a BMW E82!

*/
Enter fullscreen mode Exit fullscreen mode

When should you use "STATIC"?

You shouuld use static methods and properties whenever,

  • You're writing utility classes that don't change
  • The method should not be changes or overridden
  • The code is not dependent on instance creation

Have anything in mind ? Comment Below!

⚡Thanks For Reading | Happy Coding 😁

Discussion (0)

pic
Editor guide