簡體   English   中英

嵌套javascript函數調用中的變量范圍

[英]variables scope in nested javascript function calls

在下面的代碼中,我想知道doStuffWithReport函數中tabId的值是什么。 它將是調用sendMessage時發送的tabId的相同值,還是可能在此期間更改?

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    // we suppose that tabId is 5.
    function doStuffWithReport(report) {
       // what would be the value of tabId? still 5? or it might change to
       // something else if, in the meantime, we received another 
       // call for chrome.tabs.onUpdated?
    }
    // we are sending a message to tabId 5.
    chrome.tabs.sendMessage(tabId, {
        text: 'report_me'
    }, doStuffWithReport);
});

編輯:我自己測試了它。 它保持不變,即即使在chrome.tab.onUpdated上有另一個調用,tabId也將保持為5。

好吧,首先讓我們簡化代碼以查看底層行為:

function outside(){
  var out = 5;
  function inside(){
    console.log(out);
  }
  inside();
}

在此示例中,當調用outside時,它顯然會打印出5,但是由於inside僅在本地定義,因此除非是從outside內調用,否則它將是未定義的。

為了使其更加復雜,我們不要使它靜態,而要基於參數:

function outside(out){
  function inside(){
    console.log(out);
  }
  inside();
}

現在,它與以前幾乎相同,並且將立即打印出用作參數的內容。 讓我們通過inside最多一秒鍾的隨機時間后調用inside ,然后將out的當前值與內部調用時打印的out的值同時調用幾次來進行比較,使它更加異步連續。

function outside(out){
  function inside(){
    var dt = Date.now();
    console.log(dt + ' : ' +out);
  }
  var n = Math.floor(Math.random() * 1000);
  var d = Date.now()+n;
  console.log(d + ' : ' + out);
  setTimeout(inside,n);
}
for(var x=0;x<25;x++){outside(x);}

從此輸出中,我們可以看到inside調用時具有的out的值與設置inside調用的超時時的值相同。

由此可以說,當doStuffWithReport時, tabId的確仍為5。

暫無
暫無

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

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