I have two functions.
function function_a(callback) {
if (some_condition===true) {
callback // fire the callback
}
}
function function_b() {
... do some action
}
My script calls:
function_a(function_b());
Meaning, the callback
in function_a()
will be the execution of function_b()
.
However I do not always want function_b()
to fire. I only want it to fire when some_condition===true
(as in the function_a()
body).
The problem right now is that whenever I feed a callback function into the parameters of another function it fires it automatically without running through the script of the function to determine whether or not the callback needs to fire at all.
Is there something I am doing wrong or some different way to do this?
Thank you!
I have two functions.
function function_a(callback) {
if (some_condition===true) {
callback // fire the callback
}
}
function function_b() {
... do some action
}
My script calls:
function_a(function_b());
Meaning, the callback
in function_a()
will be the execution of function_b()
.
However I do not always want function_b()
to fire. I only want it to fire when some_condition===true
(as in the function_a()
body).
The problem right now is that whenever I feed a callback function into the parameters of another function it fires it automatically without running through the script of the function to determine whether or not the callback needs to fire at all.
Is there something I am doing wrong or some different way to do this?
Thank you!
Share Improve this question asked Dec 4, 2015 at 1:55 Walker FarrowWalker Farrow 3,9449 gold badges36 silver badges56 bronze badges 1-
1
In JavaScript, arguments are always evaluated first.
foo(bar())
executesbar
and passes its return value tofoo
. Unlessfunction_b
returns a function, your code is wrong. – Felix Kling Commented Dec 4, 2015 at 1:58
3 Answers
Reset to default 7You need to call function_a(function_b);
.
Right now you are not passing function_b
itself, you are calling it immediately and passing in its return value.
Your function_a
should do callback()
rather than callback
.
Parentheses cause a function to "execute" or "fire". So like Comptonburger said, drop the parentheses for the "script call", but add the parentheses on the callback.
function function_a(callback) {
if (some_condition === true) {
callback(); // parentheses do the "firing"
}
}
function function_b() {
// ... do some action
}
// Script calls:
// No parentheses on function_b because we
// don't want to "fire it" right here and now.
function_a( function_b );
You can also pass function_b()
as a string and evaluate it after condition passes.
function function_a(callback) {
if (some_condition===true) {
eval(callback); // fire the callback
}
}
function function_b() {
... do some action
}
function_a("function_b()");
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744642109a4585503.html
评论列表(0条)