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