0

I would like to pass a function with parameters to another function and have it run on an event, like this:

var main_object = function () {
    this.main_function = function (function) {
        document.addEventListener('click',function);
    }
    this.passed_function = function (variable) {
        alert(variable);
    }
}



var main_object = new main_object();
main_object.main_function(main_object.passed_function(3));
1
  • 2
    You should replace the parameter called "function" of main_function with something else. "function" is a reserved keyword. Commented Oct 27, 2013 at 17:27

4 Answers 4

2

In modern JavaScript engines, you can bind the function:

mainObject.main_function(main_object.passed_function.bind(main_object, 3));

The first argument to bind will be this when the function executes and any remaining arguments to bind will be leading arguments in the call to the function.

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

3 Comments

For compatibility, this link has some provided compatibility code: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… I'm going to try this out to make sure I understand it correctly.
@JVE999 - yes, thanks for pointing out the compatibility code. That's the link I have in my answer.
Ah. Thanks. I didn't notice it was a link, the color is similar to the regular text color on my screen.
1

If I understand you right,

main_object.main_function(function() { main_object.passed_function(3) });

1 Comment

This is also a helpful answer. I'm going to try it out. I'm guessing this is how the EventListener function works.
1

For what you're talking about, you could just use bind. In your case, you would do:

main_object.main_function(main_object.passed_function.bind( main_object, 3 ));

Comments

0
function mainfunc(func) {
    alert(func);
}

function callBackFn(a) {
    alert(a);
}

 

mainfunc("arg1", callBackFn("javaScritFnParameter"));  //call this in load

For sure it works no need to worry... but callbackFn will execute first and next only "arg1" will execute.

1 Comment

Wow, that's super interesting. I'm not exactly sure how that works. For anyone who's wondering, here's a jsFiddle

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.