简体   繁体   English

在Javascript中使用回调参数创建函数

[英]creating a function in Javascript with callback arguments

I want to create "foo" function which has a callback as argument, and also wanted the callback to have two arguments as mentioned below. 我想创建具有回调作为参数的“ foo”函数,并且还希望该回调具有如下所述的两个参数。 I tried, but didn't get a solution yet. 我尝试过,但是还没有解决方案。

it doesn't have any usecase it's just a challenge for myself :) 它没有任何用例,对我自己只是一个挑战:)

function foo(callback){
      callback();
}
foo((arg1,arg2)=> {
      arg1=0;
      arg2=1;
});

what should i do? 我该怎么办?

The arguments passed to the callback are created by the function calling it , so in your case foo does that: 传递给回调的参数是由调用该函数的函数创建 ,因此在您的情况下, foo

 function foo(callback){ callback(/*arg1: */ 0, /* arg2: */ 1); } foo((arg1,arg2) => { console.log("arg1 is", arg1, "arg2 is", arg2); }); 

You call a callback just like you call any other function. 您可以像调用其他任何函数一样调用回调。

fixed. 固定。

this is what i learned and i want to share with you, to create a simple callback function we can write: 这是我学到的,我想与您分享,以创建一个简单的回调函数,我们可以编写:

function foo(DoSomeThing){
     DoSomeThing();
}

and to test that : 并测试:

foo(function(){
      console.log(`Hello world`);
});

this function didn't have any arguments, so if we want to add arguments we shuold do something like : 该函数没有任何参数,因此,如果我们想添加参数,则shuold可以执行以下操作:

function foo2(doSomeThing){
      doSomeThing(argument1=0,argument2=0);
}

and to test that : 并测试:

foo2((arg1,arg2) => {
      console.log(`arg1 : ${arg1} and arg2 : ${arg2}`);
});

in this case answer is : arg1 : 0 and arg2 : 0 在这种情况下,答案是: arg1 : 0 and arg2 : 0

in the first example i used callback function and in the second one i used arrow function.it depends on you to choose any of them... 在第一个示例中,我使用了回调函数,在第二个示例中,我使用了箭头函数。这取决于您选择其中的任何一个...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM