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 badges1 Answer
Reset to default 3If 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
版权声明:本文标题:javascript - executing function based on condition - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745556191a2663201.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论