How do I pass functions as a parameter in JavaScript.
In the code below if I call whatMustHappen (TWO(),ONE()) I want to them to fall in the sequence of the x and the y on the whatMustHappen function.
Right now it fires as it sees it in the parameter.
var ONE = function() {
alert("ONE");
}
var TWO = function() {
alert("TWO");
}
var THREE = function() {
alert("THREE");
}
var whatMustHappen = function(x, y) {
y;
x;
}
whatMustHappen(TWO(), null);
whatMustHappen(TWO(), ONE());
Nikola K.
7,15313 gold badges33 silver badges39 bronze badges
asked Jul 19, 2012 at 10:20
Hello-World
9,57524 gold badges92 silver badges157 bronze badges
3 Answers 3
var whatMustHappen = function(x, y) {
if (y) y();
if (x) x();
}
whatMustHappen(TWO, null);
whatMustHappen(TWO, ONE);
answered Jul 19, 2012 at 10:22
Riz
10.3k8 gold badges43 silver badges54 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Riz
which error and why ? due to null ? OP should take care of that. Updated my answer anyway.
() invokes a function and returns its result. To pass a function, you simply pass it like any other variable:
whatMustHappen(TWO, ONE);
In whatMustHappen function, you can then call them:
var whatMustHappen = function(x, y) {
if( y ) y();
if( x ) x();
}
answered Jul 19, 2012 at 10:22
Esailija
140k24 gold badges280 silver badges328 bronze badges
Comments
If you want to pass a function, don't call it (with (args)).
function foo () {
alert("foo");
}
function bar (arg) {
alert("Function passed: " + arg);
arg();
}
bar(foo);
answered Jul 19, 2012 at 10:22
Quentin
949k137 gold badges1.3k silver badges1.4k bronze badges
Comments
lang-js