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

3
  • 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. Commented Jun 22, 2013 at 23:41
  • @elclanrs edited. sorry :) . it is just simple case, so how to do? Commented Jun 22, 2013 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 Commented Jun 23, 2013 at 0:11

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

@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 :)
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));

1 Comment

@BagusJavas: The question was tagged with jQuery, so naturally I assumed that you use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.