【问题标题】:Stack + variable behaviour堆栈 + 变量行为
【发布时间】:2014-03-17 18:13:44
【问题描述】:

我只是对理解堆栈执行和变量有点困惑。下面是代码。

  var getDetails=false;

   function firstFunction(){
      getDetails=true;

//      ajax call

   }

   function secondFunction(){
      getDetails=false;
     subFunction();
   }

    fucntion subFunction(){
        if(getDetails){

     }
    }   

你注意到有一个全局变量,我在第一个和第二个函数中设置全局变量的值,并在我的子函数中使用它。

现在假设我调用了 fistFunction(此函数进行 ajax 调用并稍晚获取数据)。 现在,当 firstFunction 正在执行时,我将在其中更改全局变量的第二个函数,并且我还调用使用全局变量的 subFucntion。现在让我们说,当子函数正在执行时,即使我的 FirstFunction 也在执行全局变量的值是多少?

【问题讨论】:

  • JavaScript 是单线程的。

标签: javascript stack


【解决方案1】:

在您上面的代码中,当您调用subFunction 时,getDetails 绝对是false,因为您在调用subFunction 之前立即将其设置为false

您对 Javascript 的工作原理有误解:

当子函数正在执行时,我的 FirstFunction 也在执行

这种情况不可能发生。

Javascript 是单线程的,因此一次只能执行一个函数。 AJAX 调用,如 setTimeout,是异步的,但回调函数只会在您的其他执行路径完成后执行,这是响应准备好后线程可用的最早点。如果线程正忙于执行另一个函数,那么您的回调将在完成之前不会运行。

试试这个例子:

var start = new Date().getTime();
// Logs first
console.log('Start time: ', start); 

// Asynchronous, but still won't run until after the spin lock finishes
// A result of Javascript being single-threaded
setTimeout(function(){
    // Logs last
    console.log('Asynchronous callback time: ', new Date().getTime());
}, 500);

// Two second spin-lock
while(start + 2000 > new Date().getTime());

// Logs second
console.log('Spin lock finished', new Date().getTime());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-15
    • 2011-04-13
    • 2014-12-09
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 2013-09-27
    • 2013-01-05
    相关资源
    最近更新 更多