-1

My problem is simple and I couldn't find the proper answer in this forum. My bad...

I want to do that :

    const dataReceived = foo;
    foo(state);

How can I do that? I read it is better to avoid eval, and I couldn't get success with new Function. Thanks for your help!

EDIT Thanks for your answers. I work with React. In my reducer, I have a create_item case. I can reach action.category, that can be the word 'currency' or 'country'.

What I want to do is to launch either the method createCurrency or createCountry according what is inside action.category. That's why I tried to join 'create' and 'action.category' to create a dynamic function name. But it seems to be a poor idea...

yaco16
  • 27
  • 4
  • 1
    Please take the [tour] and read [ask]. There's nothing in your question that would require `eval` or `new Function`. – Heretic Monkey Jan 11 '21 at 14:42
  • Should your existing code + some example data. It isn't clear what you're trying to do at all. // What actual problem are you trying to solve? Where does the string come from? – user202729 Jan 11 '21 at 14:42
  • @Liam That's one possible interpretation of the question, but yes it's kind of unclear. – user202729 Jan 11 '21 at 14:42
  • No, dont' do that. Functions are not data, and they should not be treated like data. – Teemu Jan 11 '21 at 14:43
  • @Teemu, there's no reason to not assign a function to a property, it's done all the time. That's the basis why functions are first class objects in JS – Liam Jan 11 '21 at 14:44
  • 2
    What is the value of `foo`? What role does `dataReceived` play? What is the value of `state`? You are just showing how the value of one variable is assigned to another variable and how one variable is called as a function. If `foo` holds a function value that your code works as is. Please provide more information, it's unclear what the problem is. – Felix Kling Jan 11 '21 at 14:48
  • @Liam Ehh ... What? How is that related to functions as data? Notice, that in the title OP says they want to make a function out of a string, the example doesn't make much sense in that context, but what OP says they have tried. – Teemu Jan 11 '21 at 14:48
  • 1
    With respect to your update, @rounin's answer would be the way to go. – Felix Kling Jan 11 '21 at 15:52

1 Answers1

0

The simplest approach is to create an object which contains an entry where:

  • the key is a string
  • the value is a function.

Example:

const myObject = {

  myFunction: () => { [... DO SOMETHING...] }

}

Subsequently you will be able to invoke the function, using:

myObject.myFunction();

The above becomes more powerful when you use brackets notation.

Example:

const myString = 'myFunction';

myObject[myString]();
Rounin
  • 27,134
  • 9
  • 83
  • 108