如何在Javascript中创建静态变量?
当前回答
在JavaScript中,没有静态的术语或关键字,但我们可以将这些数据直接放到函数对象中(就像在任何其他对象中一样)。
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
其他回答
您可以利用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.
这会得到相同的结果——只是这次返回的是递增的值,而不是显示。
您可以使用arguments.callee存储“静态”变量(这在匿名函数中也很有用):
function () {
arguments.callee.myStaticVar = arguments.callee.myStaticVar || 1;
arguments.callee.myStaticVar++;
alert(arguments.callee.myStaticVar);
}
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语言特性的实现(单击此处)。
阅读更多关于该特性本身的信息,以及演示静态字段语法的示例(单击此处)。
我有通用方法:
创建对象,如:stat_flags={};将其用于动态添加字段:flags.popup_save_inited=true;下次询问对象中是否需要标记并执行逻辑
例子:
class ACTGeneratedPages {
constructor(table_data, html_table_id) {
this.flags = {};//static flags for any processes
//any your code here
}
call_popup(post_id) {
let _this = this;
document.getElementById('act-popup-template').style.display = 'block';
if (!this.flags.popup_save_inited) {//second time listener will not be attached
document.querySelector('.act-modal-save').addEventListener('click', function (e) {
//saving data code here
return false;
});
}
this.flags.popup_save_inited = true;//set flag here
}
}
我使用了原型,并以这种方式工作:
class Cat {
constructor() {
console.log(Cat.COLLECTION_NAME);
}
}
Cat.COLLECTION_NAME = "cats";
或使用静态吸气剂:
class Cat {
constructor() {
console.log(Cat.COLLECTION_NAME);
}
static get COLLECTION_NAME() {
return "cats"
}
}