如何在Javascript中创建静态变量?
JavaScript中的静态变量
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):
function circle(){
}
circle.prototype.pi=3.14159
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
In JavaScript, there is no term or keyword static, but we can put such data directly into function object (like in any other object).
function f() {
f.count = ++f.count || 1 // f.count is undefined at first
alert("Call No " + f.count)
}
f(); // Call No 1
f(); // Call No 2
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:
var thisIsGlobal = 1;
function foo() {
var thisIsNot = 2;
}
The other thing you could do would be to store global variables inside an object literal like this:
var foo = { bar : 1 }
And then access the variabels like this: foo.bar
.
In JavaScript variables are static by default. Example:
var x = 0;
function draw() {
alert(x); //
x+=1;
}
setInterval(draw, 1000);
The value of x is incremented by 1 every 1000 milliseconds
It will print 1,2,3 so forth
If you are using the new class syntax then you can now do the following:
class MyClass {
static get myStaticVariable() {
return "some static variable";
}
}
console.log(MyClass.myStaticVariable);
aMyClass = new MyClass();
console.log(aMyClass.myStaticVariable, "is undefined");
This effectively creates a static variable in JavaScript.
function Person(){
if(Person.count == undefined){
Person.count = 1;
}
else{
Person.count ++;
}
console.log(Person.count);
}
var p1 = new Person();
var p2 = new Person();
var p3 = new Person();
您可以通过IIFE(立即调用的函数表达式)执行此操作:
var incr = (function () {
var i = 1;
return function () {
return i++;
}
})();
incr(); // returns 1
incr(); // returns 2
您可以使用arguments.callee来存储“静态”变量(这在匿名函数中也很有用):
function () {
arguments.callee.myStaticVar = arguments.callee.myStaticVar || 1;
arguments.callee.myStaticVar++;
alert(arguments.callee.myStaticVar);
}
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!!