在javascript中定义函数除了使用function关键字外,还可以使用函数表达式
let sayHi = function() { alert( "Hello" ); };
使用该语法可以将函数赋值给变量,sayHi。
特别需要注意的是,如果使用函数表达式定义的,结尾处需要有;号,采用function关键字的则不需要
回调函数
将函数名作为参数进行传递,称之为回调函数
function ask(question, yes, no) { if (confirm(question)) yes() else no(); } function showOk() { alert( "You agreed." ); } function showCancel() { alert( "You canceled the execution." ); } // usage: functions showOk, showCancel are passed as arguments to ask ask("Do you agree?", showOk, showCancel);
这里的showOk、showCancle作为参数传递到了ask函数里
匿名函数
不起名字的函数叫匿名函数
function ask(question, yes, no) { if (confirm(question)) yes() else no(); } ask( "Do you agree?", function() { alert("You agreed."); }, function() { alert("You canceled the execution."); } );
ask函数的第二、第三个参数称之为匿名函数,外部不可以使用