JavaScript:将参数传递给回调函数
我试图将一些参数传递给一个用作回调的函数,我该怎么做JavaScript:将参数传递给回调函数,javascript,callback,parameter-passing,Javascript,Callback,Parameter Passing,我试图将一些参数传递给一个用作回调的函数,我该怎么做 function tryMe (param1, param2) { alert (param1 + " and " + param2); } function callbackTester (callback, param1, param2) { callback (param1, param2); } callbackTester (tryMe, "hello", "goodbye"); 如果您想要更一般的内容,可以使
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester (callback, param1, param2) {
callback (param1, param2);
}
callbackTester (tryMe, "hello", "goodbye");
如果您想要更一般的内容,可以使用arguments变量,如下所示:
function tryMe (param1, param2) {
alert(param1 + " and " + param2);
}
function callbackTester (callback) {
callback (arguments[1], arguments[2]);
}
callbackTester (tryMe, "hello", "goodbye");
但除此之外,您的示例运行良好(可以在测试仪中使用参数[0]代替回调)您的问题不清楚。如果您想知道如何以更简单的方式实现这一点,那么应该看看ECMAScript第5版方法.bind(),它是Function.prototype的一个成员。使用它,您可以执行以下操作:
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester (callback) {
callback();
}
callbackTester(tryMe.bind(null, "hello", "goodbye"));
您还可以使用以下代码,如果当前浏览器中没有该方法,则会添加该代码:
// 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)));
};
};
}
这也适用于:
// callback function
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
// callback executer
function callbackTester (callback) {
callback();
}
// test function
callbackTester (function() {
tryMe("hello", "goodbye");
});
另一个场景:
// 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);
});
当您有一个回调函数,它将被代码以外的具有特定数量的参数的对象调用,并且您希望传入其他参数时,您可以传递一个包装函数作为回调函数,并在包装函数内部传递其他参数 使用函数包装器中的参数包装正在作为/传递的“子”函数,以防止在调用“父”函数时对其求值
function outcome(){
return false;
}
function process(callbackSuccess, callbackFailure){
if ( outcome() )
callbackSuccess();
else
callbackFailure();
}
process(function(){alert("OKAY");},function(){alert("OOPS");})
来自具有任意数量参数和回调上下文的问题的代码:
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
一个新版本,用于回调将由其他函数(而不是您自己的代码)调用,并且您希望添加其他参数的场景 例如,让我们假设您有很多嵌套调用,其中包含成功和错误回调。我将在本例中使用angular Promissions,但是任何带有回调的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);
});
现在,您可能希望通过定义一个记录错误的函数来整理代码,保留错误的来源以用于调试。下面是重构代码的方法:
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);
};
调用函数仍然会在回调函数参数之后添加错误参数。我也在寻找同样的问题,最终得到了解决方案,如果有人想了解这一点,这里是一个简单的示例
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')
同样在另一个问题上发布使用curried函数,如本简单示例所示
const BTN=document.querySelector('按钮')
const RES=document.querySelector('p')
const changeText=newText=>()=>{
RES.textContent=newText
}
BTN.addEventListener('click',changeText('Clicked!'))
点击我
未单击
如果不确定要将多少参数传递到回调函数中,请使用apply
函数
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester(callback,params){
callback.apply(this,params);
}
callbackTester(tryMe,['hello','goodbye']);
让我给你一个非常简单的Node.js风格的回调示例:
/**
* Function expects these arguments:
* 2 numbers and a callback function(err, result)
*/
var myTest = function(arg1, arg2, callback) {
if (typeof arg1 !== "number") {
return callback('Arg 1 is not a number!', null); // Args: 1)Error, 2)No result
}
if (typeof arg2 !== "number") {
return callback('Arg 2 is not a number!', null); // Args: 1)Error, 2)No result
}
if (arg1 === arg2) {
// Do somethign complex here..
callback(null, 'Actions ended, arg1 was equal to arg2'); // Args: 1)No error, 2)Result
} else if (arg1 > arg2) {
// Do somethign complex here..
callback(null, 'Actions ended, arg1 was > from arg2'); // Args: 1)No error, 2)Result
} else {
// Do somethign else complex here..
callback(null, 'Actions ended, arg1 was < from arg2'); // Args: 1)No error, 2)Result
}
};
/**
* Call it this way:
* Third argument is an anonymous function with 2 args for error and result
*/
myTest(3, 6, function(err, result) {
var resultElement = document.getElementById("my_result");
if (err) {
resultElement.innerHTML = 'Error! ' + err;
resultElement.style.color = "red";
//throw err; // if you want
} else {
resultElement.innerHTML = 'Result: ' + result;
resultElement.style.color = "green";
}
});
/**
*函数需要以下参数:
*2个数字和一个回调函数(err、result)
*/
var myTest=函数(arg1、arg2、回调){
如果(arg1的类型!=“编号”){
返回回调('Arg 1不是数字!',null);//Args:1)错误,2)无结果
}
如果(arg2的类型!=“编号”){
返回回调('arg2不是数字!',null);//Args:1)错误,2)无结果
}
如果(arg1==arg2){
//在这里做些复杂的事情。。
回调(null,‘操作结束,arg1等于arg2’;//Args:1)无错误,2)结果
}否则如果(arg1>arg2){
//在这里做些复杂的事情。。
回调(null,'操作结束,arg1从arg2>开始);//Args:1)无错误,2)结果
}否则{
//在这里做些其他复杂的事情。。
回调(null,'操作结束,arg1<来自arg2');//Args:1)无错误,2)结果
}
};
/**
*可以这样说:
*第三个参数是一个匿名函数,有两个参数表示错误和结果
*/
myTest(3、6、函数(错误、结果){
var resultElement=document.getElementById(“我的结果”);
如果(错误){
resultElement.innerHTML='Error!'+err;
resultElement.style.color=“红色”;
//抛出err;//如果需要
}否则{
resultElement.innerHTML='Result:'+Result;
resultElement.style.color=“绿色”;
}
});
以及将呈现结果的HTML:
<div id="my_result">
Result will come here!
</div>
结果会来的!
您可以在此处使用它:-例如,尝试传递字符串而不是数字:myTest('some string',6,function(err,result)。然后查看结果
我希望这个例子能有所帮助,因为它代表了回调函数的基本思想
function tryMe(param1, param2) {
console.log(param1 + " and " + param2);
}
function tryMe2(param1) {
console.log(param1);
}
function callbackTester(callback, ...params) {
callback(...params);
}
callbackTester(tryMe, "hello", "goodbye");
callbackTester(tryMe2, "hello");
关于扩展语法//假设函数不带任何参数意味着只添加GetAlterConfirmation(函数(结果){});
//Suppose function not taking any parameter means just add the GetAlterConfirmation(function(result) {});
GetAlterConfirmation('test','messageText',function(result) {
alert(result);
}); //Function into document load or any other click event.
function GetAlterConfirmation(titleText, messageText, _callback){
bootbox.confirm({
title: titleText,
message: messageText,
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function (result) {
return _callback(result);
}
});
GetAlterConfirmation('test','messageText',函数(结果){
警报(结果);
});//函数加载到文档或任何其他单击事件中。
函数GetAlterConfirmation(titleText、messageText、_回调){
bootbox.confirm({
标题:titleText,
message:messageText,
按钮:{
取消:{
标签:“取消”
},
确认:{
标签:“确认”
}
},
回调:函数(结果){
返回_回调(结果);
}
});
您正在做的应该可以工作。您有什么问题?您的代码工作正常,问题是什么?应该可以工作…很抱歉,这是我在主代码语法上的错误,我想这是因为这是我第一次在JavaScription中使用回调,如果您想向回调添加参数,但无法更改调用它的内容(由于您无权更改参数顺序,您可以使用JS bind预绑定一些回调参数,正如我在回答中所示:只要我们本着一般的精神,callback.apply(参数)
因为callbackTester
的函数体可扩展到两个参数的场景之外。很抱歉,这是主代码中的语法错误,我认为这是因为这是我第一次使用cal
//Suppose function not taking any parameter means just add the GetAlterConfirmation(function(result) {});
GetAlterConfirmation('test','messageText',function(result) {
alert(result);
}); //Function into document load or any other click event.
function GetAlterConfirmation(titleText, messageText, _callback){
bootbox.confirm({
title: titleText,
message: messageText,
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function (result) {
return _callback(result);
}
});