JS5 -- 回调
概念:
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
回调函数()通过参数的形式传递到另个函数,在另一个函数的方法执行完后,执行回调函数;
作用:
请求后端数据或耗时长后,依赖前面的方法或属性,用这些数据做后边的事。)
例子:Ajax请求后台数据后,把请求的数据显示在页面上。
例子:
场景
朋友聚会后各种回家,他们约定通过各种途径回家完成后,在微信群报个到!
goHomeMethod('走回家了',goHomeMethodDone)
function goHomeMethod (method,callback) { //走回家的方式
console.log(method); //朋友1走回家30分钟,朋友2骑自行车40分钟。。。。。。
callback(); //回调函数
}
//回调函数
function goHomeMethodDone () { //走回家后的报到
console.log("微信发报到消息!");
}
打印结果:
走回家了
微信发报到消息!
(如果定时器时,定时器的方法会添加到事件队列的末尾)
a('走回家了',goHomeMethodDone)
function a (method,callback) {
seTimeout(function () {
console.log(method)
})
callback();
}
打印结果:(定时器会把‘我回家了’添加到事件队列的末尾)
微信发报到消息!
走回家了
.lgyong

浙公网安备 33010602011771号