2

I want to use function in my javascript code in dynamic way like this code.

const function1 = (param) => {
    return "AA" + param
}
const function2 = (param) => {
    return "BB" + param
}
const function3 = (param) => {
    return "CC" + param
}

for (let i=1; i < 4; i++) {
    // call function1, 2, 3 with i
} 

And I saw a similar case in python like this.

note1 = "note1"
note2 = "note2"
note3 = "note3"

for i in range(1, 4):
    print(vars()[f"note{i}"])

like this python case, Is there a way that treat javascript variable or function with dynamic name?

neulhan
  • 55
  • 3
  • Make them properties of an object, so `myObj['1'] = param => {...}` then `myObj[i]()`. – RobG Jun 08 '20 at 05:52

1 Answers1

2

You can do like this:

Any function that is created outside any function, in non-strict mode, goes to default this (window). So you can access it as window[ propertyName ]. However, its a bad practice to pollute to window object. Hence better option is to wrap these functions in a custom object and then use same syntax to access functions.

const function1 = (param) => {
    return "AA" + param
}
const function2 = (param) => {
    return "BB" + param
}
const function3 = (param) => {
    return "CC" + param
}


for (let i=1; i < 4; i++) {
    window[`function${i}`](i);
}

Reference:

Rajesh
  • 24,354
  • 5
  • 48
  • 79
Deepak Dixit
  • 1,510
  • 15
  • 24