js回调函数的简单理解
什么是回调?
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed。
字面上的理解,回调函数就是传递一个参数化的函数,就是将这个函数作为一个参数传到另一个主函数里面,当那一个主函数执行完之后,再执行传进去的作为参数的函数。走这个过程的参数化的函数 就叫做回调函数。换个说法也就是被作为参数传递到另一个函数(主函数)的那个函数就叫做 回调函数。
例子:
1.基本方法
<script > function doSomething(callback) { // … // Call the callback callback(‘stuff‘, ‘goes‘, ‘here‘); } function foo(a, b, c) { // I‘m the callback alert(a + " " + b + " " + c); } doSomething(foo); </script>
或者用匿名函数的形式:
<script>
function dosomething(damsg, callback){
alert(damsg);
if(typeof callback == "function")
callback();
}
dosomething("回调函数", function(){
alert("和 jquery 的 callbacks 形式一样!");
});
</script>.call调用:
<script>
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(handle) {
// alert(this.name);
//将值传回给handle函数
handle.call(this,this.name);
// handle(this.name); --> undefind
}
// function foo() {
// alert(this.name);
// }
var t = new Thing('Joe');
t.doSomething(function(a){
alert(a);
}); // Alerts "Joe" via `foo`
</script>本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!