如果您只是在谈论有条件地执行一个函数并存储结果......
var result;
if( condition ){
result = foo();
}else{
result = bar();
}
var myVar = result;
如果要确定要调用的函数,但要等到下次再调用它,请使用:
// define some functions
function foo(){ return "foo"; }
function bar(){ return "bar"; }
// define a condition
var condition = false;
// this will store the function we want to call
var functionToCall;
// evaluate
if( condition ){
functionToCall = foo; // assign, but don't call
}else{
functionToCall = bar; // ditto
}
// call the function we picked, and alert the results
alert( functionToCall() );
回调在 JS 中可能非常有用......它们基本上告诉消费者“当你认为合适时调用它”。
ajax()
这是传递给 jQuery方法的回调示例。
function mySuccessFunction( data ){
// here inside the callback we can do whatever we want
alert( data );
}
$.ajax( {
url: options.actionUrl,
type: "POST",
// here, we pass a callback function to be executed in a "success" case.
// It won't be called immediately; in fact, it might not be called at all
// if the operation fails.
success: mySuccessFunction
} );