我遇到过这个例子:
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 中实现静态局部变量”
我知道函数变量存储在堆栈中。拥有 C 背景的我知道堆栈中的变量很容易被后续的函数调用覆盖。
JavaScript 似乎并非如此。
什么规则指定局部(函数)变量在程序的生命周期中存在多长时间?
我的意思是 Javascript 中的 stack
必须具有与 C、C++
中的 stack
不同的语义?
最佳答案
局部变量至少只要可访问就存在。通过关闭,他们甚至可以永远留下来:
function noClosure() {
let local = 3;
//...
} // local gets recycled here
function closure() {
let local = 3;
return function inner() {
return local; // <- closured
}
}
var closured = closure();
// local exists here:
console.log(closured()); // 3
// but now it might get recycled:
closured = undefined;
在您的代码片段中,它实际上不是局部变量,而是全局函数对象的属性,该属性一直存在,直到它被删除、变得不可引用或引擎停止执行:
delete countMyself.counter; // property deletion
countMyself = somethingNew; // unreferencable
关于javascript - 局部(函数)变量在 JavaScript 中存在多久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51825364/