javascript 使用箭头函数将参数传递给回调函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51190305/
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
Passing parameters to a callback function using arrow function
提问by Jaison
I know this is a duplicatedquestion with ES5, but I am looking for the syntax with ES6 arrow function. My code below:
我知道这是ES5的重复问题,但我正在寻找 ES6 箭头函数的语法。我的代码如下:
fetchItems = (callback) => {
//After ajax success
callback(response);
}
const myParams = {name:"John"}
this.fetchItems((res) => {
console.log(res.data);
});
For the above scenario, I want to pass some parameters(myParams) along with the function call, how can I achieve that?
对于上述场景,我想myParams在函数调用的同时传递一些参数(),我该如何实现?
采纳答案by Guerric P
You can do that:
你可以这样做:
const fetchItems = (callback, ...params) => {
//Do whatever you want with the params
callback(response);
}
Example of usage:
用法示例:
const fetchItems = (callback, ...params) => {
callback(params);
}
fetchItems ((res) => console.log(res), 'foo', 1);
回答by void
More of less you can do it the same way
你可以用同样的方式做更多或更少
const getCountries = (data, callback) => {
//After ajax success
callback(response);
}
getCountries("data", ()=>{});
回答by Aluok
There is a way using the defaultValue, but I don't think it's the best.
有一种使用 defaultValue 的方法,但我认为它不是最好的。
If I can find a better way, I'll update the answer.
如果我能找到更好的方法,我会更新答案。
fetchItems = (callback) => {
var response = {data: 'a'};
//After ajax success
callback(response);
}
const myParams = {name:"John"}
this.fetchItems((res, params = myParams) => {
console.log(res.data);
console.log(params);//{name:"John"}
});

