将额外的参数传递给回调函数

Pass an extra argument to a callback function

提问人:Kulin 提问时间:11/25/2016 最后编辑:Michał PerłakowskiKulin 更新时间:2/15/2022 访问量:44395

问:

我有一个函数,它将回调函数作为参数,并使用一个参数调用它。callWithMagic

const callWithMagic = callback => {
  const magic = getMagic();
  callback(magic);
};

我还有一个函数,它有两个参数:和。processMagicmagictheAnswer

const processMagic = (magic, theAnswer) => {
  someOtherMagic();
};

我想将函数作为参数传递给 ,但我也想将第二个参数 () 传递给 。我该怎么做?processMagiccallWithMagic42theAnswerprocessMagic

callWithMagic(<what should I put here?>);
JavaScript 函数 参数 回调

评论

1赞 JotaBe 11/28/2016
如果你想看到一个更彻底的答案,请看这个问题和答案,它比它早了两年:stackoverflow.com/questions/21985201/......

答:

69赞 str 11/25/2016 #1

只需创建一个包装器回调:function(magic) {}

callWithMagic(function(magic) {
  return processMagic(magic, 42);
});

或者使用 ECMAScript 6: 箭头函数:

callWithMagic(magic => processMagic(magic, 42));

评论

0赞 Kulin 11/25/2016
谢谢,这就是“工作”!但只是第一次 marketEvent 它被调用。接下来的调用将返回 newArg 值的 undefined,但不会返回其他两个值。
0赞 str 11/25/2016
@Kulin 这应该每次都有效。当你把它标记为答案时,你是否让它工作?
0赞 duplode 11/26/2016
这篇文章正在 Meta 上讨论 - meta.stackoverflow.com/q/338481(请参阅问题的评论)。同时通知提问者,@Kulin .
4赞 Dropye 11/25/2016 #2

您可以使用匿名函数

类似的东西

session.sub('Hello', function(){marketEvents(your args);});

评论

0赞 gregko 10/10/2017
这是迄今为止最好的答案,谢谢!也可以与 function() 上的参数一起使用,例如 session.sub('Hello', function(orgArg){marketEvents(orgArg, your_args);});
1赞 TryingToImprove 11/25/2016 #3

您可以创建一个调用该函数的函数。无需使事情复杂化marketEvent

session.sub('Hello', function(args, kwargs) {
    marketEvent(args, kwargs, 'my custom data');
});

否则,您可以这样做:

var mrktEvent = function(customArgs) {
    return function(args, kwargs) { 
        marketEvent(args, kwargs, customArgs) 
    };
}

session.sub('Hello', mrktEvent("customEvent"));
0赞 aecavac 5/25/2018 #4

您可以将参数对象绑定到回调函数:

var varObject = {var1: "findButton", var2: true};

function cbFunc() {
    console.log(this.var1+ ":" + this.var2);
}

//Example callback
datatable.ajax.reload(cbFunc.bind(varObject));
1赞 Teocci 9/30/2021 #5

我想将函数作为参数传递给 ,但我也想将第二个参数传递给 。我该怎么做?processMagiccallWithMagic42theAnswerprocessMagic

好的,首先,您的实现几乎接近答案。你想像这样调用你的函数。另外,我注意到您使用了 ECMAScript 6: 箭头函数,因此我们将大大简化我们的代码。callWithMagic(<what should I put here?>)

因此,可以使用这些参数,其中第一个参数是函数,另一个参数是要添加的额外参数。callWithMagic(<what should I put here?>);callWithMagic(processMagic, 42);callback

要使用额外的参数调用此函数,我们需要通过定义一个新参数来修改实现,该参数如下所示:callWithMagicanswer

const callWithMagic = (callback, answer) => {
  const magic = getMagic()
  callback(magic, answer)
}

现在,这里有一个实现的工作片段:

const spells = ["Accio", "Aguamenti", "Alohomora", "Aparecium", "Avada Kedavra", "Avifors", "Avis", "Bombarda", "Colloportus", "Confringo", "Confundus", "Crucio", "Deletrius", "Densaugeo", "Diffindo", "Dissendium", "Engorgio", "Episkey", "Evanesco", "Expecto Patronum", "Expelliarmus", "Fera Verto", "Ferula", "Fidelius", "Finite Incantatem", "Flagrate", "Flipendo", "Furnunculus", "Geminio", "Homorphus", "Immobulus", "Impedimenta", "Imperio", "Impervius", "Incarcerous", "Incendio", "Legilimens", "Levicorpus", "Liberacorpus", "Locomotor Mortis", "Lumos", "Mobiliarbus", "Mobilicorpus", "Morsmordre", "Muffliato", "Nox", "Obliviate", "Orchideous", "Petrificus Totalus", "Prior Incantato", "Protego", "Reducio", "Reducto", "Relashio", "Rennervate", "Reparo", "Repello", "Repello Muggletum", "Revelio", "Rictusempra", "Riddikulus", "Salvio Hexia", "Scourgify", "Sectumsempra", "Serpensortia", "Silencio", "Sonorus", "Stupefy", "Tarantallegra", "Tergeo", "Waddiwasi", "Wingardium Leviosa"]
const len = spells.length

function random(max) {
  return Math.floor(Math.random() * max)
}

const getMagic = () => {
  return spells[random(len)]
}

const callWithMagic = (callback, answer) => {
  const magic = getMagic()
  callback(magic, answer)
}

const someOtherMagic = (magic, answer) => {
  console.log({magic, answer})
}

const processMagic = (magic, answer) => {
  someOtherMagic(magic, answer)
}

callWithMagic(processMagic, 42)

Teo,看起来不错,但它很长,我们能简化一下吗?

是的。我们只需要闭合的概念。这个想法是创建一个包装器回调,如.这将是 的参数。现在让我们修改以接收包装器回调:function() {}callWithMagiccallWithMagic

const callWithMagic = function(f) {
  f()
}

或使用箭头函数:

const callWithMagic = f => f()

让我们看看它是如何工作的:

const spells = ["Accio", "Aguamenti", "Alohomora", "Aparecium", "Avada Kedavra", "Avifors", "Avis", "Bombarda", "Colloportus", "Confringo", "Confundus", "Crucio", "Deletrius", "Densaugeo", "Diffindo", "Dissendium", "Engorgio", "Episkey", "Evanesco", "Expecto Patronum", "Expelliarmus", "Fera Verto", "Ferula", "Fidelius", "Finite Incantatem", "Flagrate", "Flipendo", "Furnunculus", "Geminio", "Homorphus", "Immobulus", "Impedimenta", "Imperio", "Impervius", "Incarcerous", "Incendio", "Legilimens", "Levicorpus", "Liberacorpus", "Locomotor Mortis", "Lumos", "Mobiliarbus", "Mobilicorpus", "Morsmordre", "Muffliato", "Nox", "Obliviate", "Orchideous", "Petrificus Totalus", "Prior Incantato", "Protego", "Reducio", "Reducto", "Relashio", "Rennervate", "Reparo", "Repello", "Repello Muggletum", "Revelio", "Rictusempra", "Riddikulus", "Salvio Hexia", "Scourgify", "Sectumsempra", "Serpensortia", "Silencio", "Sonorus", "Stupefy", "Tarantallegra", "Tergeo", "Waddiwasi", "Wingardium Leviosa"]
const len = spells.length

const random = max => Math.floor(Math.random() * max)

const callWithMagic = callback => callback()

const getMagic = () => spells[random(len)]

const someOtherMagic = (magic, answer) => console.log({magic, answer})

const processMagic = (magic, answer) => someOtherMagic(magic, answer)

callWithMagic(function() {
  const magic = getMagic()
  return processMagic(magic, 42)
})

现在让我们简化为 .callWithMagicconst callWithMagic = f => f()

const magic = getMagic()
callWithMagic(magic => processMagic(magic, 42))

const spells = ["Accio", "Aguamenti", "Alohomora", "Aparecium", "Avada Kedavra", "Avifors", "Avis", "Bombarda", "Colloportus", "Confringo", "Confundus", "Crucio", "Deletrius", "Densaugeo", "Diffindo", "Dissendium", "Engorgio", "Episkey", "Evanesco", "Expecto Patronum", "Expelliarmus", "Fera Verto", "Ferula", "Fidelius", "Finite Incantatem", "Flagrate", "Flipendo", "Furnunculus", "Geminio", "Homorphus", "Immobulus", "Impedimenta", "Imperio", "Impervius", "Incarcerous", "Incendio", "Legilimens", "Levicorpus", "Liberacorpus", "Locomotor Mortis", "Lumos", "Mobiliarbus", "Mobilicorpus", "Morsmordre", "Muffliato", "Nox", "Obliviate", "Orchideous", "Petrificus Totalus", "Prior Incantato", "Protego", "Reducio", "Reducto", "Relashio", "Rennervate", "Reparo", "Repello", "Repello Muggletum", "Revelio", "Rictusempra", "Riddikulus", "Salvio Hexia", "Scourgify", "Sectumsempra", "Serpensortia", "Silencio", "Sonorus", "Stupefy", "Tarantallegra", "Tergeo", "Waddiwasi", "Wingardium Leviosa"]
const len = spells.length

const random = max => Math.floor(Math.random() * max)

const callWithMagic = f => f()

const getMagic = () => spells[random(len)]

const someOtherMagic = (magic, answer) => console.log({magic, answer})

const processMagic = (magic, answer) => someOtherMagic(magic, answer)

callWithMagic(() => {
  const magic = getMagic()
  processMagic(magic, 42)
})