分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

js 回调函数理解与应用

发布时间:2023-09-06 01:17责任编辑:郭大石关键词:js回调函数

  定义:在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

js 回调函数理解与应用

原文地址:http://www.cnblogs.com/mengqi-S/p/7657945.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved