JavaScript:将参数传递给回调函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3458553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Passing parameters to a callback function
提问by vitto
I'm trying to pass some parameter to a function used as callback, how can I do that?
我试图将一些参数传递给用作回调的函数,我该怎么做?
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester (callback, param1, param2) {
callback (param1, param2);
}
callbackTester (tryMe, "hello", "goodbye");
采纳答案by Simon Scarfe
If you want something slightly more general, you can use the arguments variable like so:
如果你想要更一般的东西,你可以像这样使用参数变量:
function tryMe (param1, param2) {
alert(param1 + " and " + param2);
}
function callbackTester (callback) {
callback (arguments[1], arguments[2]);
}
callbackTester (tryMe, "hello", "goodbye");
But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)
但除此之外,您的示例工作正常(参数 [0] 可用于代替测试器中的回调)
回答by Marimuthu Madasamy
This would also work:
这也可以:
// callback function
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
// callback executer
function callbackTester (callback) {
callback();
}
// test function
callbackTester (function() {
tryMe("hello", "goodbye");
});
Another Scenario :
另一个场景:
// callback function
function tryMe (param1, param2, param3) {
alert (param1 + " and " + param2 + " " + param3);
}
// callback executer
function callbackTester (callback) {
//this is the more obivous scenario as we use callback function
//only when we have some missing value
//get this data from ajax or compute
var extraParam = "this data was missing" ;
//call the callback when we have the data
callback(extraParam);
}
// test function
callbackTester (function(k) {
tryMe("hello", "goodbye", k);
});
回答by Andy E
Your question is unclear. If you're asking how you can do this in a simpler way, you should take a look at the ECMAScript 5th edition method .bind(), which is a member of Function.prototype. Using it, you can do something like this:
你的问题不清楚。如果您问如何以更简单的方式执行此操作,您应该查看 ECMAScript 第 5 版方法.bind(),它是Function.prototype的成员。使用它,您可以执行以下操作:
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester (callback) {
callback();
}
callbackTester(tryMe.bind(null, "hello", "goodbye"));
You can also use the following code, which adds the method if it isn't available in the current browser:
您还可以使用以下代码,如果该方法在当前浏览器中不可用,则会添加该方法:
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
回答by Blake Mills
When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param(s).
当您有一个回调,该回调将被具有特定数量参数的代码以外的其他东西调用,并且您想传入额外的参数时,您可以传递一个包装函数作为回调,并在包装器内部传递额外的参数。
function login(accessedViaPopup) {
//pass FB.login a call back function wrapper that will accept the
//response param and then call my "real" callback with the additional param
FB.login(function(response){
fb_login_callback(response,accessedViaPopup);
});
}
//handles respone from fb login call
function fb_login_callback(response, accessedViaPopup) {
//do stuff
}
回答by Zeeman Chen
If you are not sure how many parameters are you going to be passed into callback functions, use applyfunction.
如果您不确定将有多少参数传递到回调函数中,请使用applyfunction。
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester(callback,params){
callback.apply(this,params);
}
callbackTester(tryMe,['hello','goodbye']);
回答by Alan McCune
Wrap the 'child' function(s) being passed as/with arguments within function wrappers to prevent them being evaluated when the 'parent' function is called.
在函数包装器中包装作为/带有参数传递的“子”函数,以防止在调用“父”函数时对它们进行评估。
function outcome(){
return false;
}
function process(callbackSuccess, callbackFailure){
if ( outcome() )
callbackSuccess();
else
callbackFailure();
}
process(function(){alert("OKAY");},function(){alert("OOPS");})
回答by Adam Skobodzinski
Code from a question with any number of parameters and a callback context:
来自具有任意数量参数和回调上下文的问题的代码:
function SomeFunction(name) {
this.name = name;
}
function tryMe(param1, param2) {
console.log(this.name + ": " + param1 + " and " + param2);
}
function tryMeMore(param1, param2, param3) {
console.log(this.name + ": " + param1 + " and " + param2 + " and even " + param3);
}
function callbackTester(callback, callbackContext) {
callback.apply(callbackContext, Array.prototype.splice.call(arguments, 2));
}
callbackTester(tryMe, new SomeFunction("context1"), "hello", "goodbye");
callbackTester(tryMeMore, new SomeFunction("context2"), "hello", "goodbye", "hasta la vista");
// context1: hello and goodbye
// context2: hello and goodbye and even hasta la vista
回答by Adam Skobodzinski
Use curried function as in this simple example.
在这个简单的例子中使用柯里化函数。
const BTN = document.querySelector('button')
const RES = document.querySelector('p')
const changeText = newText => () => {
RES.textContent = newText
}
BTN.addEventListener('click', changeText('Clicked!'))
<button>ClickMe</button>
<p>Not clicked<p>
回答by Juangui Jordán
A new version for the scenario where the callback will be called by some other function, not your own code, and you want to add additional parameters.
一个新版本,用于回调将由某个其他函数而不是您自己的代码调用的场景,并且您想要添加其他参数。
For example, let's pretend that you have a lot of nested calls with success and error callbacks. I will use angular promises for this example but any javascript code with callbacks would be the same for the purpose.
例如,假设您有很多带有成功和错误回调的嵌套调用。我将在此示例中使用 angular 承诺,但任何带有回调的 javascript 代码都将用于此目的。
someObject.doSomething(param1, function(result1) {
console.log("Got result from doSomething: " + result1);
result.doSomethingElse(param2, function(result2) {
console.log("Got result from doSomethingElse: " + result2);
}, function(error2) {
console.log("Got error from doSomethingElse: " + error2);
});
}, function(error1) {
console.log("Got error from doSomething: " + error1);
});
Now you may want to unclutter your code by defining a function to log errors, keeping the origin of the error for debugging purposes. This is how you would proceed to refactor your code:
现在,您可能希望通过定义一个记录错误的函数来整理代码,保留错误的来源以进行调试。这是您重构代码的方式:
someObject.doSomething(param1, function (result1) {
console.log("Got result from doSomething: " + result1);
result.doSomethingElse(param2, function (result2) {
console.log("Got result from doSomethingElse: " + result2);
}, handleError.bind(null, "doSomethingElse"));
}, handleError.bind(null, "doSomething"));
/*
* Log errors, capturing the error of a callback and prepending an id
*/
var handleError = function (id, error) {
var id = id || "";
console.log("Got error from " + id + ": " + error);
};
The calling function will still add the error parameter after your callback function parameters.
调用函数仍会在回调函数参数之后添加错误参数。
回答by Code_Crash
I was looking for the same thing and end up with the solution and here it's a simple example if anybody wants to go through this.
我一直在寻找同样的东西并最终得到解决方案,如果有人想通过这个,这是一个简单的例子。
var FA = function(data){
console.log("IN A:"+data)
FC(data,"LastName");
};
var FC = function(data,d2){
console.log("IN C:"+data,d2)
};
var FB = function(data){
console.log("IN B:"+data);
FA(data)
};
FB('FirstName')
Also posted on the other question here
也在这里发布了另一个问题

