我试图理解JS中的回调。以下是我现在正在处理的例子:
getData('http://fakedomain1234.com/userlist', writeData);
document.getElementById('output').innerHTML += "show this before data ...";
function getData(dataURI, callback) {
// Normally you would actually connect to a server here.
// We're just going to simulate a 3-second delay.
var timer = setTimeout(function () {
var dataArray = [123, 456, 789, 012, 345, 678];
callback(dataArray);
}, 3000);
}
function writeData(myData) {
document.getElementById('output').innerHTML += myData;
}
我的问题是:是否可以将匿名函数传递给getData()
而不是已经定义的函数?如果是这样,你会怎么做到这一点?
先谢谢!
答案 0 :(得分:2)
就像您传递给getData('http://fakedomain1234.com/userlist', function(myData) {
document.getElementById('output').innerHTML += myData;
});
Schedule
答案 1 :(得分:1)
就像你说的那样:
getData('http://fakedomain1234.com/userlist', function(data) {
// contents of anonymous function
});