简体   繁体   中英

JS - how to pass function as parameter (with parameters) without invoking it

I have this method:

myFunction: function(a,b,c) { 
   ... 
}

Now, I want to pass it as parameter to another method so it can be executed inside that method:

...
var a = "bla";
var b = "ble";
var c = "bli";
someFunction(myFunction(a,b,c),true,"test");

And then inside someFunction I would like to call myFunction like:

someFunction: function(func,bool,str){
   func();
}

Is that possible?

Thanks

Yes, but you have to create a function that makes the function call, ie bind (aka "curry") the function reference with the parameters:

someFunction(myFunction.bind(this, a, b, c), true, "test");

Some older browsers (eg IE 8) doesn't support the bind method, but you can do basically the same with a function expression:

someFunction(function() { myFunction(a, b, c); }, true, "test");

If you are using jQuery there is a $.proxy method that takes care of making it browser independent:

someFunction($.proxy(myFunction, this, a, b, c), true, "test");

Yes, this is possible in JavaScript.

someFunction(function () {
    myFunction(a,b,c);
}, true, "test");

You can even do:

var myFunc = function () {
    myFunction(a,b,c);
};
someFunction(myFunc, true, "test");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM