定义:在JavaScript中,回调函数具体的定义为:函数A作为参数(函数引用)传递到另一个函数B中,并且这个函数B执行函数A。我们就说函数A叫做回调函数。如果没有名称(函数表达式),就叫做匿名回调函数。

  理解:回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

  举个例子:

//首先,创建通用诗的生成函数;它将作为下面的getUserInput函数的回调函数

    function genericPoemMaker(name, gender) {
console.log(name + " is finer than fine wine.");
console.log("Altruistic and noble for the modern time.");
console.log("Always admirably adorned with the latest style.");
console.log("A " + gender + " of unfortunate tragedies who still manages a perpetual smile");
} //callback,参数的最后一项,将会是我们在上面定义的genericPoemMaker函数
function getUserInput(firstName, lastName, gender, callback) {
var fullName = firstName + " " + lastName; // Make sure the callback is a function
if (typeof callback === "function") {
// Execute the callback function and pass the parameters to it
callback(fullName, gender);
}
}
getUserInput("Michael", "Fassbender", "Man", genericPoemMaker); // 输出 /* Michael Fassbender is finer than fine wine. Altruistic and noble for the modern time. Always admirably adorned with the latest style. A Man of unfortunate tragedies who still manages a perpetual smile. */

我们可以换一个回调函数试试: function greetUser(customerName, sex) {
var salutation = sex && sex === "Man" ? "Mr." : "Ms.";
console.log("Hello, " + salutation + " " + customerName);
} // 将greetUser作为一个回调函数
getUserInput("Bill", "Gates", "Man", greetUser); // 这里是输出
Hello, Mr. Bill Gates

最新文章

  1. centos 下git服务器搭建
  2. J2EE之oracle、mysql存储过程调用
  3. BZOJ树链剖分题目汇总
  4. [lintcode 14] First Position of Target
  5. AngularJS $http
  6. innodb_fast_shutdown中值为1或者2的区别是?
  7. Weblogic控制器的部署
  8. Android2.2 API —— ImageView
  9. Vanya and Triangles 暴力枚举
  10. python模块学习:os模块
  11. VS2010每次调试都出现“此项目已经过期”提示
  12. Jetson Nano Developer Kit
  13. 生鲜配送管理系统_升鲜宝V2.0 小标签打印功能【代配送商品打印小标签功能】说明_15382353715
  14. iOS 10 设备权限问题(相机,相册等)
  15. Java中反射机制详解
  16. 实现用VB.Net/(C#)开发K/3 BOS 插件的真正可行方法
  17. PostgreSQL事务实现
  18. Java学习技术分享:Java中的原子操作
  19. python + lisp hy的新手注记1
  20. <山月记>:中岛敦 -选段

热门文章

  1. POJ 2871
  2. POJ 2636
  3. POJ 2572
  4. CentOS 6.5 安装和使用Gitlab
  5. php -- 文件读写
  6. 08 - JavaSE之IO流
  7. React技术栈梳理
  8. 从Java进程里dump出类的字节码文件
  9. ELK常用命令
  10. JAVA WEB 三器之过滤器(Filter)