[英]Passing function with parameters as parameter of another function in JavaScript
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));
In modern JavaScript engines, you can bind
the function: 在现代JavaScript引擎中,您可以bind
函数:
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. 函数执行时,要bind
的第一个参数将是this
参数,而要bind
其余所有参数将成为函数调用中的前导参数。
如果我没听错,
main_object.main_function(function() { main_object.passed_function(3) });
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. 当然,它的工作无需担心...但是callbackFn将首先执行,然后仅执行“ arg1”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.