How can I create static variables in Javascript?
Join them; it only takes a minute:
If you come from a class-based, strongly typed object-oriented language (like Java, C++ or C#) I assume that you are trying to create a variable or method associated to a "type" but not to an instance. An example using a "classical" approach, with constructor functions maybe could help you to catch the concepts of basic OO JavaScript:
|
|||||||||||||||||||||
|
You might take advantage of the fact that JS functions are also objects -- which means they can have properties. For instance, quoting the example given on the (now vanished) article Static variables in Javascript:
If you call that function several time, you'll see the counter is being incremented. And this is probably a much better solution than poluting the global namespace with a global variable.
Which gets you the same kind of result -- except, this time, the incremented value is returned, instead of displayed. |
|||||||||||||||||||||
|
You do it through an IIFE (immediately invoked function expression):
|
|||||
|
you can use arguments.callee to store "static" variables (this is useful in anonymous function too):
|
|||||||||||||||||
|
|
|||
|
I've seen a couple of similar answers, but I'd like to mention that this post describes it best, so I'd like to share it with you. Here's some code taken from it, which I have modified to get a complete example which hopefully gives benefit to the community because it can be used as a design template for classes. It also answers your question:
Given that example, you can access the static properties/function as follows:
And the object properties/functions simply as:
Note that in podcast.immutableProp(), we have a closure: The reference to _somePrivateVariable is kept inside the function. You can even define getters and setters. Take a look at this code snippet (where
It defines the property What is also valid is this syntax:
which defines a readable/writable property Notes: To avoid unexpected behaviour in case you've forgotten the
Now both of the following instantiations will work as expected:
Note also, that in some situations it can be useful to use the The article series I've mentioned above are highly recommended to read, they include also the following topics:
Note that the automatic semicolon insertion "feature" of JavaScript (as mentioned in 6.) is very often responsible for causing strange issues in your code. Hence, I would rather regard it as a bug than as a feature. If you want to read more, here is a quite interesting MSDN article about these topics, some of them described there provide even more details. What is interesting to read as well (also covering the topics mentioned above) are those articles from the MDN JavaScript Guide: Those of you who are working with IE (which has no console for JavaScript unless you open the developer tools using F12 and open the console tab) might find the following snippet useful. It allows you to use
For your convenience, here's the code above in one complete single code snippet:
|
||||
|
The following example and explanation are from the book Professional JavaScript for Web Developers 2nd Edition by Nicholas Zakas. This is the answer I was looking for so I thought it would be helpful to add it here.
The |
|||||||||||||||||||||
|
Updated answer: In ECMAScript 6, you can create static functions using the
ES6 classes don't introduce any new semantics for statics. You can do the same thing in ES5 like this:
You can assign to a property of |
|||||||||||||||||
|
If you want to declare static variables for creating constants in your application then I found following as most simplistic approach
|
|||
|
There are other similar answers, but none of them quite appealed to me. Here's what I ended up with:
|
|||
|
If you wanted to make a global static variable:
Replace the variable with the below:
|
|||
|
The closest thing in JavaScript to a static variable is a global variable - this is simply a variable declared outside the scope of a function or object literal:
The other thing you could do would be to store global variables inside an object literal like this:
And then access the variabels like this: |
|||||
|
There's another approach, which solved my requirements after browsing this thread. It depends on exactly what you want to achieve with a "static variable". The global property sessionStorage or localStorage allows data to be stored for the life of the session, or for an indefinite longer period until explicitly cleared, respectively. This allows data to be shared among all windows, frames, tab panels, popups etc of your page/app and is much more powerful than a simple "static/global variable" in one code segment. It avoids all hassle with the scope, lifetime, semantics, dynamics etc of top-level global variables, ie Window.myglobal. Don't know how efficient it is, but that's not important for modest amounts of data, accessed at modest rates. Easily accessed as "sessionStorage.mydata = anything" and retrieved similarly. See "JavaScript: The Definitive Guide, Sixth Edition", David Flanagan, ISBN: 978-0-596-80552-4, Chapter 20, section 20.1. This is easily downloadable as a PDF by simple search, or in your O'Reilly Safaribooks subscription (worth its weight in gold). Cheers, Greg E |
||||
|
To condense all class concepts here, test this:
Well, another way to take a look to best practices in these things, is to just see how coffeescript translates these concepts.
|
||||
|
You can create a static variable in JavaScript like this below. Here
You can assign values to the static variable using either the
|
||||
|
Window level vars are sorta like statics in the sense that you can use direct reference and these are available to all parts of your app |
|||||
|
There is no such thing as an static variable in Javascript. This language is prototype-based object orientated, so there are no classes, but prototypes from where objects "copy" themselves. You may simulate them with global variables or with prototyping (adding a property to the prototype):
|
|||||||||||||
|
Working with MVC websites that use jQuery, I like to make sure AJAX actions within certain event handlers can only be executed once the previous request has completed. I use a "static" jqXHR object variable to achieve this. Given the following button:
I generally use an IIFE like this for my click handler:
|
||||
|
If you want to use prototype then there is a way
Doing this you will be able to access the counter variable from any instance and any change in the property will be immediately reflected!! |
|||
|
So what I see with the other answers is that they don't address the fundamental architectural requirement of a static attribute in object oriented programming. Object oriented programming actually has two different styles one is 'class based' (C++, C#, Java etc), the other is 'prototypal' (Javascript). In class based languages a 'static attribute' is supposed to be associated with the class and not the instantiated objects. This concept actually works much more intuitively in a prototypal languages like Javascript because you just assign the attribute as a value of the parent prototype like so.
And access it from every one of the objects that is instantiated from this constructor like so...
Now if you go ahead and change the However there are a few 'gotchas' that could significantly undermine the 'static' nature of this attribute, or just leave security vulnerability... First make sure to hide the constructor from the Global namespace by enclosing it inside another function like the jQuery ready method
Second and lastly, even if you do this, the attribute is still editable from any of the other parts of your own script, so it could be the case that a bug in your code writes over the attribute on one of the child objects and detaches it from the parent prototype, so if you change the parent attribute it will no longer cascade and change the static attribute for the child object. See this jsfiddle. In different scenarios we could either It seems to me that there is not a perfect analogue between the class-based idea of a 'static attribute' and this Javascript implementation. So I think it might be better in the long run to use a different code pattern that is more Javascript friendly. Such as a central datastore or cache or even a dedicated helper object to hold all the necessary static variables. |
|||
|
I didn't see this idea in any of the answers so just adding it to the list. If it's a duplicate just let me know and i'll delete it and upvote the other. I created a sort of super global in my website. Since I have several js files that are loaded on every page load and dozens of other js files that are only loaded on some pages I put all of the "global" function into a single global variable. At the top of my first included "global" files is the declaration
Then I delcare several global helper functions
Then if I need a static variable I just store it outside scope such as outside the document ready or outside the behavior attachment. (I use jquery but it should work in javascript)
This of course is a global not a static but as it is reinitialized on every page load it accomplishes the same purpose. |
|||
|
In JavaScript, there is no term or keyword static, but we can put such data directly into function object (like in any other object).
|
||||
|
For private static variables, I found this way:
|
|||||
|
Try this one: If we define a property and override its getters and setters to use the Function Object property then in theory you can have an static variable in javascript for example:
|
|||
|
'Class' System
|
|||||||||
|
You can think like this. Into the Of course you can manage the text inside the previous tag by using jquery. Pratically this tag become your static variable. |
||||
|
This is just another way of having a static variable that I learned somewhere. |
|||||||||
|
I remember JavaScript Closures when I See this.. Here is how i do it..
|
|||||
|
protected by Travis J Nov 23 '16 at 22:17
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?