Asked 7 years ago
10 Jan 2017
Views 960
fatso

fatso posted

static variable in JavaScript ?

how to create static variable in JavaScript ?
david

david
answered Apr 24 '23 00:00

In JavaScript, you can create static variables by using the static keyword in a class declaration. The static keyword indicates that a variable or method belongs to the class itself, rather than to an instance of the class.

Here's an example:



class Car {
  static numberOfWheels = 4;

  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
}

console.log(Car.numberOfWheels); // outputs: 4

const myCar = new Car('Toyota', 'Camry');

console.log(myCar.numberOfWheels); // outputs: undefined

In this example, we define a Car class with a numberOfWheels static variable set to 4 . We can access this static variable using the class name Car . When we create a new instance of the Car class with the new keyword, the numberOfWheels variable is not available on the instance [b] mycar , because it belongs to the class itself. [/b]

It's important to keep in mind that not all versions of JavaScript support static variables and methods, particularly older versions. Therefore, you may need to use a different approach to achieve similar functionality if you need to support older browsers or platforms.
Post Answer