In JavaScript, there is no direct way to define a static variable (a variable that belongs to a class rather than an instance of a class). However, you can achieve similar behavior by defining a property on the constructor function.
Here’s an example:
function User(name) {
if (typeof User.counter == 'undefined') {
User.counter = 0;
}
this.name = name;
User.counter++;
}
let user1 = new User("John");
let user2 = new User("Jane");
console.log(User.counter); // Output: 2
In the example above, we define a property counter
on the User
constructor function. When we create an instance of User
, we increment the counter
property. Since the property is attached to the constructor function, it remains the same across all instances, giving the appearance of a static variable.
Note that this approach only works for properties that don’t depend on instance data. For properties that depend on instance data, you’ll need to use a different approach, such as defining a static method on the constructor function.
+ There are no comments
Add yours