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

IT技术 javascript function parameters callback
2021-02-01 09:39:38

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

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

我还有一个函数processMagic,它接受两个参数:magictheAnswer

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

我想将该函数processMagic作为参数传递callWithMagic,但我也想42作为第二个参数 ( theAnswer) 传递给processMagic我怎样才能做到这一点?

callWithMagic(<what should I put here?>);
5个回答

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

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

或者使用ECMAScript 6:箭头函数

callWithMagic(magic => processMagic(magic, 42));
@Kulin 这应该每次都有效。当您将其标记为答案时,您让它工作了吗?
2021-03-12 09:39:38
这篇文章正在 Meta 上进行讨论 - meta.stackoverflow.com/q/338481(请参阅对问题的评论)。同时通知提问者@Kulin。
2021-03-25 09:39:38
谢谢,这就是“工作”!但只有第一次调用 marketEvent 时。下一次调用为 newArg 值返回 undefined,但不为其他两个调用返回。
2021-04-08 09:39:38

您可以使用匿名功能

就像是

session.sub('Hello', function(){marketEvents(your args);});
这是迄今为止最好的答案,谢谢!也可以与 function() 上的参数一起使用,例如 session.sub('Hello', function(orgArg){marketEvents(orgArg, your_args);});
2021-03-26 09:39:38

您可以创建一个调用该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"));

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

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

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

//Example callback
datatable.ajax.reload(cbFunc.bind(varObject));

我想将函数processMagic作为参数传递callWithMagic,但我也想42作为第二个参数传递theAnswerprocessMagic我怎样才能做到这一点?

好的,首先,您的实现几乎接近答案。你想像这样调用你的函数callWithMagic(<what should I put here?>);

因此,callWithMagic(<what should I put here?>);应该替换callWithMagic(processMagic, 42);为第一个参数是callback函数,另一个是您要添加的额外参数。

为了能够使用额外参数调用此函数,我们需要callWithMagic通过定义一个新参数来修改实现,answer如下所示:

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, theAnswer) => {
  console.log({
    magic,
    theAnswer
  })
};

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

callWithMagic(processMagic, 42);