根据条件执行功能

时间:2012-08-17 04:29:33

标签: javascript

我想写这样的东西:

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包含已经调用的函数的结果。

我缺少什么让这项工作?

感谢。

1 个答案:

答案 0 :(得分: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中非常有用......它们基本上告诉消费者“在你认为合适的时候调用它”。

以下是传递给jQuery ajax()方法的回调示例。

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
 } );