我有一个类似于下面的代码。
function test(){
return function(){
setInterval(//Another Function Reference // ,1000);
}
}
我正在打电话给test()();
我看到上面的代码无法正常工作。有人可以解释一下为什么吗?
最佳答案
您的代码1中没有闭包。 test
返回一个函数对象,但是不执行[function]。在代码段中,内部函数中使用了3个闭包,将返回的函数对象分配给变量,然后执行该变量。返回功能对象的优点是可以将其分配给不同的值并分别执行。
1问题的早期版本提到“关闭不起作用”
// startInterval: interval 1 second, message: 'Hello' (default)
var startInterval = test(null, 1000);
// anotherInterval: interval 5 seconds, message: ''Hello to you too''
var anotherInterval = test('<i>Hello to you too</i>', 5000);
// execute the function objects
startInterval();
anotherInterval();
// [hithere], [time] and [result] are closed over
function test(hithere, time){
hithere = hithere || 'Hello';
time = time || 1000;
var result = document.querySelector('#result');
return function(){
setInterval(function(){
result.innerHTML += hithere+'<br>';
},time || 1000);
}
}
<div id="result">Greetings!<hr></div>
关于javascript - 返回函数内的setInterval不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27819108/