将匿名 JS 函数作为回调传递
Passing anonymous JS function as a callback
我正在尝试了解 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()
而不是已定义的函数?如果是这样,您将如何做到这一点?
就像你说的:
getData('http://fakedomain1234.com/userlist', function(data) {
// contents of anonymous function
});
就像你传递给setTimeout
的函数一样
getData('http://fakedomain1234.com/userlist', function(myData) {
document.getElementById('output').innerHTML += myData;
});
我正在尝试了解 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()
而不是已定义的函数?如果是这样,您将如何做到这一点?
就像你说的:
getData('http://fakedomain1234.com/userlist', function(data) {
// contents of anonymous function
});
就像你传递给setTimeout
getData('http://fakedomain1234.com/userlist', function(myData) {
document.getElementById('output').innerHTML += myData;
});