Pass parameters to a function being passed from parameter to parameter

Asked

Viewed 40 times

1

Imagine this, I have the function 1 that needs to receive as a parameter a function callback.

Function 2 needs to receive a parameter and I need to pass it as a function value1, as I would pass this value "message" in function 2 and I have to call it in 1?

function funcao1(cb) {
  return cb();
}

function funcao2(message) {
  console.log(message)
}

funcao1(funcao2)

1 answer

3


Can’t do exactly that, can something close. The function signature cb does not predict that it has parameters, so you cannot pass a function that has this parameter.

One solution is to change funcao() why cb() accept parameter and also accept a parameter to be passed. I think it is not what you want, what you want is not possible.

function funcao1(cb, message) {
    return cb(message);
}

function funcao2(message) {
    console.log(message);
}

funcao1(funcao2, "ok");

I put in the Github for future reference.

Another possibility is to use an enclosure, so the message goes along:

function funcao1(cb) {
  return cb();
}

var message = "ok";

function funcao2() {
  console.log(message);
}

funcao1(funcao2);

I put in the Github for future reference.

That’s not exactly a closure (is a global, enclosing if you were inside a function), but passes the idea of how it works, can put the funcao2() and message inside another function that is there the way I am talking, even because it must be so that it will actually be in real code.

It should not be what you want yet, but it is the alternatives. You can have new alternatives understanding the real problem, maybe not even need all this. The artificial example is not bad to explain the basics, but does not give room for other alternatives.

Still have user140828 option in comment below:

function funcao1(cb) {
    return cb();
}

function funcao2(message) {
    console.log(message);
}

funcao1(() => funcao2("ok"));

I put in the Github for future reference.

You create a indirect extra, but I still see that doing so may not make much sense. I think you need to take a closer look at the real problem.

  • 1

    I would also suggest using funcao1(() => funcao2('ok')), but I did not understand very well what the author of the question wants.

  • @user140828 good, put the credit to you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.