先来看看什么是回调函数(callback)
回调函数就是调用函数的时候将另一个函数的名称当作参数传递进去,并且在函数体中进行调用。
function study(){ console.log("studying..."); } function play(){ console.log("playing..."); } function sleep(){ console.log("sleeping...."); } function doWhat(funName){ console("我正在"); funName(); } doWhat(study);//我正在studying... doWhat(play);//我正在playing... doWhat(sleep);//我正在sleeping...
带参数的
function study(name){ console.log(name+" "+"studying..."); } function play(name){ console.log(name+" "+"playing..."); } function sleep(name){ console.log(name+" "+"sleeping...."); } function doWhat(funName,name){ funName(name); } doWhat(study,‘xiaoming‘);//xiaoming studying... doWhat(play,‘xiaodong‘);//xiaodong playing...
也可以带很多参数,我们写一个计算的例子
function add(a,b){ console.log(a+b); } function reduce(a,b){ console.log(a-b); } function calc(funName,fn1,fn2){ funName(fn1,fn2); } calc(add,5,4);//9calc(reduce,5,4);//1
这就是回调函数(callback);
希望对你理解回调函数有帮助
(完
时间: 2024-10-14 04:38:28