簡體   English   中英

本地(函數)變量在 javascript 中存在多長時間

[英]How long local(function) variables live in 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 中實現靜態局部變量”

我知道函數變量存儲在堆棧中。 C背景我知道stack中的變量很容易被后續的函數調用覆蓋。

這似乎不是 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM