0

Is there a way to name a function base on a string?

Scenario:

I need to create an array of funcs. For this I'm looping through an array of objects, and the idea would be to name the function based on the object.name.

Ideally for objects named a and b, funcs would have [func1_a, func2_a, func1_b, func2_b]

Example:

let types = [
  {
    'name': 'a',
    'key': 'a_key',
    'value': 'this is a value',
  },
  {
    'name': 'b',
    'key': 'b_key',
    'value': 'this is b value',
  }
];
let funcs = [];
for (const type in types) {
  test.push(
    function func1_{type.name} {
      // do something with type.key and type.value
    },
    function func2_{type.name} {
      // do something with type.key and type.value
    }
 )
}

Problem

I know function func1_{type.name} is not correct, thus I'm trying to find the way to do this. Any ideas? Or something like this is even possible?

Note: most of the resources I found are how to call a function based on a string, but nothing on how to name/create a function based on a string.

Thanks in advance!

2
  • 1
    Why do you want to add a name at all? What are you going to use it for? (Given that you push them into an array, so you are likely going to execute them by index anyway, plus names of named function expression are only really accessible from that function itself.) Commented May 13, 2021 at 22:27
  • Unfortunately I minimized the scenario, and just by looking at my original post I agree, I can avoid the name. In the real scenario, the list of functions is passed to a testing suite, that reads the name of the functions and prints them. Thus it would be ideal to build the functions with different names. Commented May 13, 2021 at 23:23

5 Answers 5

1

Instead of an array use an object and you can create functions and call them later on.

let types = [{
    'name': 'a',
    'key': 'a_key',
    'value': 'this is a value',
  },
  {
    'name': 'b',
    'key': 'b_key',
    'value': 'this is b value',
  }
];
let funcs = {};

for (const type in types) {
  funcs["func1_" + types[type].name] = function(params) {
    console.log(params);
  }
  
  funcs["func2_" + types[type].name] = function(params) {
    console.log(params);
  }
}

funcs["func1_a"]("test");
funcs["func2_a"]("test2");

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this approach allows you to call it like funcs.func1_a("test") as well.
0

a good way would be to use dicts instead :


let types = [
  {
    'name': 'a',
    'key': 'a_key',
    'value': 'this is a value',
  },
  {
    'name': 'b',
    'key': 'b_key',
    'value': 'this is b value',
  }
];
let funcs = [];
const test = {}
types.forEach(({name, key, value}, index) => test[`func${index}_name`] = () => {
    // anything you want 
})

Comments

0

You can have object of functions and call those like this...

let functions = {
  func1: function(string){
    console.log(string)
  }
}
let callFunctionString = "func1"
functions[callFunctionString]("hello world")

Comments

0

The eval() function evaluates JavaScript code represented as a string.

let types = [
    {
        'name': 'a',
        'key': 'a_key',
        'value': 'this is a value',
    },
    {
        'name': 'b',
        'key': 'b_key',
        'value': 'this is b value',
    }
];
// generate function
for (let inc in types) {
    let code = 'function ' + types[inc]['name'] + '(' + types[inc]['key'] + ') {console.log( "hello "+' + types[inc]['key'] + '+" !");}';
    eval(code);
}
// call function
for (let inc in types) {
    let code = types[inc]['name'] + '("' + types[inc]['value'] + '")';
    eval(code);
}

Comments

0

    let types = [
      {
        //0 : 'abc',
        'name': 'a',
        'key': 'a_key',
        'value': 'this is a value',
      },
      {
        'name': 'b',
        'key': 'b_key',
        'value': 'this is b value',
      }
    ];
    
    funcs = [];
    for(const i in types){
        let j = window["funcs"+i+"_"+types[i].name] = () => { console.log(types[i].value) }
        funcs.push(j);
    }
    console.log(funcs);
    funcs0_a(); funcs1_b();

If you want to check whether they are added in the window:

var f = Object.keys(window).filter(function(x){
    if (!(window[x] instanceof Function)) return false;
    return !/\[native code\]/.test(window[x].toString()) ? true : false;
});

console.log(f);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.