如何在Javascript中创建静态变量?
当前回答
更新答案:
在ECMAScript 6中,可以使用static关键字创建静态函数:
class Foo {
static bar() {return 'I am static.'}
}
//`bar` is a property of the class
Foo.bar() // returns 'I am static.'
//`bar` is not a property of instances of the class
var foo = new Foo()
foo.bar() //-> throws TypeError
ES6类没有为静态引入任何新的语义。您可以在ES5中这样做:
//constructor
var Foo = function() {}
Foo.bar = function() {
return 'I am static.'
}
Foo.bar() // returns 'I am static.'
var foo = new Foo()
foo.bar() // throws TypeError
您可以指定Foo的属性,因为在JavaScript中,函数是对象。
其他回答
您可以利用JS函数也是对象这一事实,这意味着它们可以具有财产。
例如,引用Javascript中静态变量一文(现已消失)中给出的示例:
function countMyself() {
// Check to see if the counter has been initialized
if ( typeof countMyself.counter == 'undefined' ) {
// It has not... perform the initialization
countMyself.counter = 0;
}
// Do something stupid to indicate the value
alert(++countMyself.counter);
}
如果多次调用该函数,您将看到计数器正在递增。
这可能是一个比用全局变量替换全局命名空间更好的解决方案。
下面是基于闭包的另一种可能的解决方案:在javascript中使用静态变量的技巧:
var uniqueID = (function() {
var id = 0; // This is the private persistent value
// The outer function returns a nested function that has access
// to the persistent value. It is this nested function we're storing
// in the variable uniqueID above.
return function() { return id++; }; // Return and increment
})(); // Invoke the outer function after defining it.
这会得到相同的结果——只是这次返回的是递增的值,而不是显示。
您可以通过IIFE(立即调用的函数表达式)执行此操作:
var incr = (function () {
var i = 1;
return function () {
return i++;
}
})();
incr(); // returns 1
incr(); // returns 2
{
var statvar = 0;
function f_counter()
{
var nonstatvar = 0;
nonstatvar ++;
statvar ++;
return statvar + " , " + nonstatvar;
}
}
alert(f_counter());
alert(f_counter());
alert(f_counter());
alert(f_counter());
这只是我在某处学到的另一种静态变量的方法。
如果你想使用原型,那么有一种方法
var p = function Person() {
this.x = 10;
this.y = 20;
}
p.prototype.counter = 0;
var person1 = new p();
person1.prototype = p.prototype;
console.log(person1.counter);
person1.prototype.counter++;
var person2 = new p();
person2.prototype = p.prototype;
console.log(person2.counter);
console.log(person1.counter);
这样做,您将能够从任何实例访问计数器变量,并且属性中的任何更改都将立即反映出来!!
摘要:
在ES6/ES 2015中,class关键字与附带的静态关键字一起引入。请记住,这是javavscript所体现的原型继承模型的语法糖。static关键字对方法的工作方式如下:
类狗{静态树皮(){console.log('wof');}//类是隐藏的函数对象//树皮方法位于Dog函数对象上makeSound(){console.log('bark');}//makeSound位于Dog.prototype对象上}//要创建静态变量,只需在类的原型上创建一个属性Dog.prototype.breed=“Pitbull”;//因此,要定义静态属性,我们不需要“static”关键字。const蓬松=新狗();const vicky=新狗();控制台.日志(绒毛.品种,vicky.品种);//更改静态变量会更改所有对象上的静态变量Dog.prototype.breed=“梗”;控制台.日志(绒毛.品种,vicky.品种);