2016-04-22 58 views
0
someOperation.then(function(x) { 
    things.forEach(function(thing) { 
     //doing something with 'thing' that depends on variable 'x' 
    }); 
}); 

在上面的代码中,如何在回调函数中使变量'x'可用?或者我必须回到这种情况下使用for循环?将参数传递给Array.forEach回调函数

+1

你有权访问x作为关闭 –

+0

@ Gonzalo.-好的,我改了一下我的代码。我仍然可以访问x作为闭包吗?因为当我在forEach回调函数中放置一个断点时,在闭包列表中看不到'x'。 – AyushISM

+2

被列在该列表中,您必须实际将其用作封闭。如果不是的话,你的js宇宙的所有变量都是可访问的。只需在你的函数中使用它(即打印它与console.log),你会看到它列出 –

回答

0

它是可用的。

let x = { 
 
    name: 'Mike' 
 
}; 
 
['Hello', 'Goodbye'].forEach(function(greeting) { 
 
    document.querySelector('pre').innerHTML += greeting + ', ' + x.name + '\n'; 
 
});
<pre></pre>

你用什么在这里被称为一个closure,是JavaScript的一个常用功能。基本上,任何函数都可以访问其父范围中的任何其他变量。

function log(msg) { 
 
    document.querySelector('pre').innerHTML += msg + '\n'; 
 
} 
 

 
var global = 'global'; 
 
function firstLevel(third) { 
 
    var first = 'first'; 
 
    
 
    // `global` is in the parent scope so we can access it 
 
    log(global + ' -> ' + first); 
 
    
 
    function secondLevel() { 
 
    var second = 'second'; 
 
    
 
    // Same thing with `first` here 
 
    log(global + ' -> ' + first + ' -> ' + second); 
 
    
 
    // This even works with passed in arguments 
 
    log(global + ' -> ' + first + ' -> ' + second + ' -> ' + third); 
 
    
 
    // We can even change closed over variables 
 
    first = 'fourth?'; 
 
    } 
 
    
 
    secondLevel(); 
 
    log(first); // Notice that `first` changed. 
 
} 
 

 
log(global); 
 
firstLevel('third'); // Notice how `third` is used in `secondLevel`
<pre></pre>

+0

好的我改变了一下我的代码。我仍然可以访问x作为闭包吗? – AyushISM

+1

@AyushISM是的,你还在。我添加了一个使用参数的例子。它的工作原理是一样的。你可以通过在自己的代码中使用'console.log(x)'来证明这一点。 –

0

您可以通过一个 “thisArg” 作为第二个参数的forEach因此,例如:

let x = { a: 123 }; 
things = ['foo', 'bar'] 
things.forEach(function(thing) { 
    alert(this.a + thing); 
}, x); 

可能会根据你正在尝试做的是有益的。