0

我想写这样的东西:

function MyFunction () { .... return SomeString; }
function SomeFunction () { ... return SomeOtherString; }

function SomeCode() {

  var TheFunction;

  if (SomeCondition) {

    TheFunction = SomeFunction;

  } else {

    TheFunction = SomeCode;
  }

  var MyVar = TheFunction(); // bugs here
}

基本上,我想在评估某些条件后执行一个函数,以便 MyVar 包含的变量包含已调用函数的结果。

我缺少什么来完成这项工作?

谢谢。

4

1 回答 1

3

如果您只是在谈论有条件地执行一个函数并存储结果......

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
 } );
于 2012-08-17T04:31:40.170 回答