简体   繁体   English

JS-如何在不调用函数的情况下将函数作为参数传递(带有参数)

[英]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中,我想像这样调用myFunction:

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: 是的,但是您必须创建一个进行函数调用的函数,即将函数引用与参数绑定 (也称为“ curry”):

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: 一些较旧的浏览器(例如IE 8)不支持bind方法,但是您可以使用函数表达式执行基本相同的操作:

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: 如果您使用的是jQuery,则可以使用$.proxy方法来使其独立于浏览器:

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

Yes, this is possible in JavaScript. 是的,这在JavaScript中是可能的。

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

You can even do: 您甚至可以:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 传入 function 参数而不调用 function - Pass in function parameter without invoking function 您可以将参数传递给函数而不立即调用它吗? - Can you pass parameters to a function without invoking it right away? 如何在不调用函数的情况下将函数作为对象的一部分传递给javascript - how to pass a function as part of an object in javascript without invoking the function 如何在不特别调用return函数的情况下使用ramda来处理多个参数 - How to curry multiple parameters with ramda without specifically invoking the return function 如何传递包含参数作为参数的JavaScript函数 - How to Pass a JavaScript function that contains parameters as parameter 如何在不调用 function 的情况下将参数传递给 function? - How to pass parameters to function without calling function? 将带有参数的函数作为参数传递,但是哪个参数需要调用函数的参数? - Passing a function with parameters as a parameter, but which takes the parameter of the invoking function? 当函数在js中有三个参数时,如何只传递第二个参数的值? - How to pass only 2nd parameter's value while function has three parameters in js? 如何将参数传递给JS函数而不将其包装在匿名函数中? - How do I pass a parameter into a JS function without wrap it in an anonymous function? 如何在不调用它的情况下传递带有参数的 function - How to pass a function with a parameter without calling it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM