js回调函数
类别:Web前端 浏览量:556
时间:2014-12-5 js回调函数
js回调函数一、什么是Javascript 回调函数?
3、因为函数在Javascript中是第一类对象,我们像对待对象一样对待函数,因此我们能像传递变量一样传递函数,在函数中返回函数,在其他函数中使用函数。当我们将一个回调函数作为参数传递给另一个函数是,我们仅仅传递了函数定义。我们并没有在参数中执行函数。我们并不传递像我们平时执行函数一样带有一对执行小括号()的函数。
4、需要注意的很重要的一点是回调函数并不会马上被执行。
1、 避免重复代码
4、使代码更容易阅读
5、 编写更多特定功能的函数
3、setTimeout和setInterval方法
//注意到click方法中是一个函数而不是一个变量
//它就是回调函数
$("#btn_1").click(function() {
alert("Btn 1 Clicked");
});
var friends = ["Mike", "Stacy", "Andy", "Rick"];
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick
});
五、允许多重回调函数
我们可以将不止一个的回调函数作为参数传递给一个函数,就像我们能够传递不止一个变量一样。
jQuery中AJAX函数就是典型:
function successCallback(){
//在发送之前做点什么
}
function successCallback(){
//在信息被成功接收之后做点什么
}
function completeCallback(){
//在完成之后做点什么
}
function errorCallback(){
//当错误发生时做点什么
}
$.ajax({
url:"http://fiddle.jshell.net/favicon.png",
success:successCallback,
complete:completeCallback,
error:errorCallback
});
六、创建自己的回调函数
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函数并将genericPoemMaker函数作为回调函数: 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.
因为getUserInput函数仅仅只负责提取数据,我们可以把任意回调函数传递给它。例如,我们可以传递一个greetUser函数:
unction 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
标签:回调函数
热门推荐
- webui控件在前端开发中的作用(HTML5 weui使用笔记)
- python数据分割教程(python3对拉勾数据进行可视化分析的方法详解)
- docker搭建私有dns域名解析(docker内网搭建dns使用域名访问替代ip:port的操作)
- pandas读取excel数据教程(详解pandas库pd.read_excel操作读取excel文件参数整理与实例)
- dedecms关闭站点(dedecms搬家后出现/include/templets/default/index.htm Not Found!解决方案)
- python获取日期(Python根据当前日期取去年同星期日期)
- mysql存储过程声明(MySQL存储过程的深入讲解in、out、inout)
- volume怎么添加docker(docker volume删除卷的操作)
- python教程列表排序(Python一行代码实现快速排序的方法)
- phpcurl详解(解决PHP curl或file_get_contents下载图片损坏或无法打开的问题)