How can I create static variables in Javascript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
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).
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.
If you come from a class-based, statically 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:
staticProperty
is defined in the MyClass object (which is a function) and has nothing to do with its created instances, JavaScript treats functions as first-class objects, so being an object, you can assign properties to a function.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
d
is the object's prototype for which you want to declare a property,y
is a private variable not visible outside of the constructor):It defines the property
d.year
viaget
andset
functions - if you don't specifyset
, then the property is read-only and cannot be modified (be aware you will not get an error if you try to set it, but it has no effect). Each property has the attributeswritable
,configurable
(allow to change after declaration) andenumerable
(allow to use it as enumerator), which are per defaultfalse
. You can set them viadefineProperty
in the 3rd parameter, e.g.enumerable: true
.What is also valid is this syntax:
which defines a readable/writable property
a
, a readonly propertyb
and a write-only propertyc
, through which propertya
can be accessed.Usage:
Notes:
To avoid unexpected behaviour in case you've forgotten the
new
keyword, I suggest that you add the following to the functionPodcast
:Now both of the following instantiations will work as expected:
The 'new' statement creates a new object and copies all properties and methods, i.e.
Note also, that in some situations it can be useful to use the
return
statement in the constructor functionPodcast
to return a custom object protecting functions the class internally relies on but which need to be exposed. This is explained further in chapter 2 (Objects) of the article series.You can say that
a
andb
inherit fromPodcast
. Now, what if you want to add a method to Podcast that applies to all of them aftera
andb
have been instanciated? In this case, use the.prototype
as follows:Now call
a
andb
again:You can find more details about prototypes here. If you want to do more inheritance, I suggest looking into this.
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:
If you want to know how to emulate c#
out
parameters (like inDateTime.TryParse(str, out result)
) in JavaScript, you can find sample code here.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
console.log(msg);
as used in the examples above. Just insert it before thePodcast
function.For your convenience, here's the code above in one complete single code snippet:
Notes:
Some good tips, hints and recommendations about JavaScript programming in general you can find here (JavaScript best practices) and there ('var' versus 'let'). Also recommended is this article about implicit typecasts (coercion).
A convenient way to use classes and compile them into JavaScript is TypeScript. Here is a playground where you can find some examples showing you how it works. Even if you're not using TypeScript at the moment, you can have a look because you can compare TypeScript with the JavaScript result on a side-by-side view. Most examples are simple, but there is also a Raytracer example which you can try out instantly. I recommend especially looking into the "Using Classes", "Using Inheritance" and "Using Generics" examples by selecting them in the combobox - these are nice templates you can instantly use in JavaScript.
To achieve encapsulation of local variables, functions etc in JavaScript, I suggest to use a pattern like the following (JQuery uses the same technique):
Of course, you can - and should - put the script code in a separate *.js file; this is just written inline to keep the example short.
If you are using the new class syntax then you can now do the following:
This effectively creates a static variable in JavaScript.
About the
class
introduced by ECMAScript 2015. The other answers are not totally clear.Here is an example showing how to create a static var
staticVar
with theClassName
.var
synthax:To access the static variable we use the
.constructor
property that returns a reference to the object constructor function that created the class. We can call it on the two created instances: