admin管理员组

文章数量:1431398

I want to write something like this:

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

function SomeCode() {

  var TheFunction;

  if (SomeCondition) {

    TheFunction = SomeFunction;

  } else {

    TheFunction = SomeCode;
  }

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

Basically, I'd like to execute a function after some condition has been evaluated so that variable MyVar contains contains the result of the function that has been called.

What am I missing to make this work?

Thanks.

I want to write something like this:

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

function SomeCode() {

  var TheFunction;

  if (SomeCondition) {

    TheFunction = SomeFunction;

  } else {

    TheFunction = SomeCode;
  }

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

Basically, I'd like to execute a function after some condition has been evaluated so that variable MyVar contains contains the result of the function that has been called.

What am I missing to make this work?

Thanks.

Share Improve this question asked Aug 17, 2012 at 4:29 frenchiefrenchie 52.1k117 gold badges320 silver badges528 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

If you are just talking about conditionally executing a function and storing the results...

var result;

if( condition ){
   result = foo();
}else{
   result = bar();
}

var myVar = result;

If you want to determine the function to call, but not call it until another time, use:

// 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() );

Callbacks can be very useful in JS...they basically tell the consumer to "call this when you think it's appropriate".

Here's an example of a callback passed to the jQuery ajax() method.

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

本文标签: javascriptexecuting function based on conditionStack Overflow