Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/478.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_Closures_Scope_Scope Chain - Fatal编程技术网

javascript在作用域链中操纵值

javascript在作用域链中操纵值,javascript,closures,scope,scope-chain,Javascript,Closures,Scope,Scope Chain,我一直在阅读Javascript闭包和作用域链,但我没有看到任何关于从作用域链中手动上传变量的内容。下面是我遇到的类似情况: function first() { var a = []; a.push({firstFunction: 'yes'}); doSomethingFunction(valueToPassIn, function() { a.push({secondFunction: 'yes'}); doAnotherThingFunction(newV

我一直在阅读Javascript闭包和作用域链,但我没有看到任何关于从作用域链中手动上传变量的内容。下面是我遇到的类似情况:

function first() {
  var a = [];
  a.push({firstFunction: 'yes'});

  doSomethingFunction(valueToPassIn, function() {
    a.push({secondFunction: 'yes'});

    doAnotherThingFunction(newValueToPassIn, function() {
      a.push({thirdFunction: 'yes'});
    })
  })

  console.log(a) //returns {firstFunction: 'yes'}
}
如何让它返回
{firstFunction:'yes',secondFunction:'yes',thirdFunction:'yes'}

代码可能有语法错误,但这正是我试图理解的想法。我只是在飞行中编写了这段代码,这样你们就可以看到类似的场景,就像我试图修复的一样


谢谢

我知道这在评论中得到了回答,但这里有一个使用回调的示例

function first(callback) {
  var a = [];
  a.push({firstFunction: 'yes'});

  doSomethingFunction(valueToPassIn, function() {
    a.push({secondFunction: 'yes'});

    doAnotherThingFunction(newValueToPassIn, function() {
      a.push({thirdFunction: 'yes'});
      callback(a);
    });

  });
}

first(function(a){ console.log(a); });
此方法唯一的问题是,当您有3个或4个以上的嵌套回调函数时,它会变得难以控制。承诺是解决问题的方法


jsidle:

doSomethingFunction
还是
doNothingFunction
异步的?如果是,那么你不能这样做。你必须在回调中执行逻辑,或者使用承诺。是的,它们是异步的,那么这是日常异步问题的重复。它与作用域或闭包无关,而是与代码的执行顺序有关,因为它是异步的。因为它们是异步的,所以必须将
console.log()
放入
doSomethingFunction
s
函数
参数中。