Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
嵌套javascript函数调用中的变量作用域_Javascript_Google Chrome Extension - Fatal编程技术网

嵌套javascript函数调用中的变量作用域

嵌套javascript函数调用中的变量作用域,javascript,google-chrome-extension,Javascript,Google Chrome Extension,在下面的代码中,我想知道doStuffWithReport函数中tabId的值是多少。是调用sendMessage时发送的tabId值相同,还是在这段时间内可能会发生变化 chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { // we suppose that tabId is 5. function doStuffWithReport(report) { // what woul

在下面的代码中,我想知道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.onUpdate上有另一个调用,tabId仍将保持为5。

好吧,首先让我们简化代码,看看底层行为:

function outside(){
  var out = 5;
  function inside(){
    console.log(out);
  }
  inside();
}
在本例中,当调用
外部
时,它显然会打印出5,但由于
内部
仅在本地定义,因此除非从
外部
内部调用,否则它将是未定义的

为了让它更复杂一点,我们不要把它写成静态的,而是基于一个参数:

function outside(out){
  function inside(){
    console.log(out);
  }
  inside();
}
现在它和以前几乎一样,将立即打印出我们用作参数的任何内容。让我们通过在长达一秒钟的随机时间后调用
inside
,将out的当前值与调用inside时打印的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);}
功能外部(外部){
函数内部(){
var dt=Date.now();
console.log(dt+':'+out);
}
var n=Math.floor(Math.random()*1000);
var d=日期。现在()+n;
console.log(d+':'+out);
setTimeout(内部,n);
}

对于(var x=0;x)回答得很好!我自己也检查过了..它将保持不变。