【javascript】回调函数

时间:2021-09-02 11:36:05

1. 定义

回调函数,即当条件满足时执行的函数。有三种方法实现调用回调函数 call

1)call

用法:call(thisObj, Obj)

主要区别:call 方法会将函数对象上下文修改为thisObj 指定的新对象。如果无thisObj , 则thisObj 为Global 对象

参数为单个,即obj

2) apply

用法:apply(thisObj, [argArray])
主要区别:call 方法会将函数对象上下文修改为thisObj 指定的新对象。如果无thisObj , 则thisObj 为Global 对象

参数为数组,可多个

3) $.proxy  

用法:$.proxy(thisObj, context)  或 $(select).proxy(context, name)

主要区别:jquery利用call,apply的实现的替换指定上下文

2. 例子

// 简单函数对象替换
function add(a, b) {
console.log('i am callFunc1, this: ', a+b);
console.log(this);
} function sub() {
console.log('i am callFunc2, this: ', a-b);
console.log(this);
} add.call(sub, 5, 4); // 此时执行add 函数,其this 对象转变为sub 函数
add.apply(sub, [5, 4]); // 对象替换
function Animal(name){
this.name = name;
this.showName = function(){
console.log(this);
console.log(this.name);
}
} function Cat(name){
this.name = name;
} var animal = new Animal("animal");
var cat = new Cat("cat"); //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。
animal.showName.call(cat,","); //执行showName 函数时,this对象已为cat 对象,所以输入结果为"Cat"
animal.showName.apply(cat,[]); // 对象继承
function Animal(name){
this.name = name;
this.age = 14;
this.showName = function(){
console.log(this);
console.log(this.name);
}
} function Cat(name){
Animal.call(this, name); // 通过call 方法继承Animal 对象的函数及属性
} var cat = new Cat("Cat");
cat.showName();

3. 长得有点像的方法

1)caller

用法:func.caller

主要区别:返回调用该函数的上层函数,如果没有上层函数,则返回null, 个人感觉没啥用

// caller 的用法
function add(a, b) {
console.log('i am add , result: ', a+b);
if (add.caller) {
console.log('add caller: ',add.caller.toString());
}else {
console.log("this is a top function");
}
sum(a, b);
}
function sub(a, b) {
console.log('i am sub , result: ', a-b);
add(a, b);
} function sum(a, b) {
console.log('i am sum , result: ', a+b);
if (sum.caller) {
console.log('sum caller: ',sum.caller.toString());
}else {
console.log("this is a top function");
}
}
add(3, 4); // 将仅输出结果,因为此时add 为第一层方法
sub(3, 4); // 将仅输出结果和上一层 方法,因为此时add 的上层方法为sub, sum 的上层方法为add

2)callee

用法:arguments.callee

主要区别:返回正在执行的函数,可用于写递归

// callee 的用法
//用于验证参数
function calleeLengthDemo(arg1, arg2) {
console.log(arguments.callee);
if (arguments.length==arguments.callee.length) {
console.log("验证形参和实参长度正确!");
return;
}else {
console.log("实参长度:" +arguments.length);
console.log("形参长度: " +arguments.callee.length);
}
}
calleeLengthDemo(4, 4, 8); // 使用callee实现递归计算
var sum = function(n) {
if (n == 1){
return 1;
}else {
return n + arguments.callee(n - 1);
}
}
console.log(sum(4)); // 一般的递归函数:
var sum = function(n){
if (1==n) {
return 1;
}else {
return n + sum (n-1);
}
}
console.log(sum(4));