Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a static variable in Javascript [duplicate]

In the following code, I would like to have a counter to keep track of the number of Person objects created. This code is not doing so, how would I accomplish that?

function Person(){     this.name = "Peter";     this.counter = this.counter + 1;     alert(this.counter); }  Person.prototype.counter = 0;  var p1 = new Person; var p2 = new Person; 
like image 802
indianwebdevil Avatar asked Sep 05 '11 11:09

indianwebdevil


People also ask

Can static variables be declared twice?

Yes it is. Each of your b variables is private to the function in which they are declared. Show activity on this post. b in func and b in main are two different variables, they are not related, and their scope is inside each function that they are in.

How do I create a static variable in JavaScript?

Static variable in JavaScript: We used the static keyword to make a variable static just like the constant variable is defined using the const keyword. It is set at the run time and such type of variable works as a global variable. We can use the static variable anywhere.

Can I change static variable value in JavaScript?

JavaScript const can be used with objects and arrays also. The value for a static variable can be reassigned. The value for a const variable cannot be reassigned. However, we can re-declare the const variable in different block scope as it is allowed.

Can we overwrite static variable?

Can we override a static method? No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time.


1 Answers

function Person(){     this.name = "Peter";     Person.counter++;     alert(Person.counter); }  Person.counter = 0;  var p1 = new Person(); var p2 = new Person(); 

Make the "static" variable a property of the Person function, rather than the prototype, and use Person instead of this inside the constructor.

This is possible because JavaScript functions are first-class (i.e. they are objects), so can have properties of their own.

Here's a working example of the above code.

like image 162
James Allardice Avatar answered Sep 21 '22 20:09

James Allardice