1

there a some similar questions, but im still confused. because my case is function with params as parameter to another function.

Simple case:

var who = 'Old IE',
dowhat  = 'eat',
mycode  = 'my code :(',
text    = 'I dont know why';

function whathappen(who, dowhat, mycode) {
    alert(who + dowhat + mycode);
}

function caller(text, func) {
    alert(text);
    func();
}

question: how to do something like caller(text, whathappen(who, dowhat, mycode)); ? im not sure if we use anonymous function like caller(text, function(){ ... } (would that anonymous func. called twice?)

Thank you

Raekye
  • 5,081
  • 8
  • 49
  • 74
Bagus Javas
  • 123
  • 3
  • 10
  • `do` is a reserved word, see the syntax highlighting? Is that your real variable name? In the first example you're not passing a function tough, but `undefined`. – elclanrs Jun 22 '13 at 23:41
  • @elclanrs edited. sorry :) . it is just simple case, so how to do? – Bagus Javas Jun 22 '13 at 23:54
  • It is passing undefined in your first usage example because it's executing `whathappened(who, dowhat, mycode)`, which doesn't return anything. So what gets passed as the parameter is `undefined` – Raekye Jun 23 '13 at 00:11

2 Answers2

3

To pass a function to be executed with arguments, you can use a lambda. The lambda is passed as the parameter func.

Example: (this is the invocation of caller - text, who, dowhat, and mycode are parameters/variables. the lambda still has access to who, dowhat, and mycode because of closures)

caller(text, function () {
    whathappen(who, dowhat, mycode);
});

As for "would that anonymous func. called twice?", if I understand what you mean, no. Maybe you have seen syntax like

(function () {
    ...
})();

Which is a lambda that is called immediately after creation (notice the parenthesis at the end "invoking" the lambda). In the first example, you are only creating and passing the anonymous function (functions are first class objects in Javascript).

Community
  • 1
  • 1
Raekye
  • 5,081
  • 8
  • 49
  • 74
  • 1
    @BagusJavas no worries. I think this is a good question. I remember when I first understood lambdas and closures and callbacks - it opens up a world of awesome stuff :) – Raekye Jun 23 '13 at 00:22
2

You can use the proxy method to make a function that calls another function with specific values:

caller(text, $.proxy(whathappen, this, who, dowhat, mycode));
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • @BagusJavas: The question was tagged with jQuery, so naturally I assumed that you use it. – Guffa Jun 23 '13 at 09:10