如何在Javascript中创建静态变量?
当前回答
2021更新
在2021,您可以简单地使用static关键字
截至2021 4月,TC39将STATIC关键字移至第4阶段语言功能。将静态JS特性变成一组正式的JS语言特性需要很长时间,然而,等待的原因是缺乏浏览器支持;现在,主流浏览器支持static关键字,并支持公共静态字段和私有静态字段的开放季节。
下面是实现静态JavaScript类成员的新方法的一般示例
class ColorFinder {
static #red = "#ff0000";
static #green = "#00ff00";
static #blue = "#0000ff";
static colorName(name) {
switch (name) {
case "red": return ColorFinder.#red;
case "blue": return ColorFinder.#blue;
case "green": return ColorFinder.#green;
default: throw new RangeError("unknown color");
}
}
// Somehow use colorName
}
以上示例取自TC39存储库,静态字段
要了解更多关于这个新的JS语言特性的实现(单击此处)。
阅读更多关于该特性本身的信息,以及演示静态字段语法的示例(单击此处)。
其他回答
如果你想使用原型,那么有一种方法
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);
这样做,您将能够从任何实例访问计数器变量,并且属性中的任何更改都将立即反映出来!!
Javascript中没有静态变量。这种语言是基于原型的面向对象的,因此没有类,而是对象“复制”自己的原型。
您可以使用全局变量或原型(向原型添加属性)来模拟它们:
function circle(){
}
circle.prototype.pi=3.14159
当我看到这个时,我记得JavaScript闭包。。我是这样做的。。
function Increment() {
var num = 0; // Here num is a private static variable
return function () {
return ++num;
}
}
var inc = new Increment();
console.log(inc());//Prints 1
console.log(inc());//Prints 2
console.log(inc());//Prints 3
您可以使用static关键字在JavaScript中定义静态函数:
class MyClass {
static myStaticFunction() {
return 42;
}
}
MyClass.myStaticFunction(); // 42
在撰写本文时,您仍然无法在类中定义静态财产(函数除外)。静态财产仍然是第三阶段的建议,这意味着它们还不是JavaScript的一部分。然而,没有什么可以阻止您像分配给任何其他对象一样简单地分配给类:
class MyClass {}
MyClass.myStaticProperty = 42;
MyClass.myStaticProperty; // 42
最后一点:小心使用带有继承的静态对象-所有继承的类共享对象的相同副本。
我没有在任何答案中看到这个想法,所以只是将其添加到列表中。如果是重复的,请告诉我,我会删除它并对另一个进行投票。
我在我的网站上创建了一种超级全球化。由于每次页面加载时都会加载几个js文件,而其他几十个js文件只加载在一些页面上,所以我将所有“全局”函数都放在一个全局变量中。
在我第一个包含的“全局”文件的顶部是声明
var cgf = {}; // Custom global functions.
然后我删除了几个全局助手函数
cgf.formBehaviors = function()
{
// My form behaviors that get attached in every page load.
}
然后,如果我需要一个静态变量,我只需将其存储在范围之外,例如文档就绪或行为附件之外。(我使用jquery,但它应该在javascript中工作)
cgf.first = true;
$.on('click', '.my-button', function()
{
// Don't allow the user to press the submit twice.
if (cgf.first)
{
// first time behavior. such as submit
}
cgf.first = false;
}
这当然是一个全局的,而不是静态的,但由于它在每次加载页面时都会重新初始化,所以它可以达到相同的目的。