DWQA QuestionsCategory: ProgramHow do you call a function like this?
Ten forty-eight asked 4 months ago
function aaa(){
  console.log('1')
}

var fnName = 'aaa'



[fnname] () // an error will be reported

If you want to use the string as the function name, is there any way?

,Just specify the object, the name of your example[fnName]()Change it like thiswindow[fnName]()You can run in a browser environment.
But if you want better compatibility, create an object yourself, like this:

<script>

var myproject = {}

myproject.aaa = function () {
  console.log('1')
}

var fnName = 'aaa'

myproject[fnName]() 

</script>

,Square brackets are strings, but the calling object cannot be omitted. The function you define is under the window object in the browser, so you shouldwindow[fnName]()Call like this
The above answer is very careful. It is the safest to define an object without a window object.
If you want to delete the answer, the result will be deducted. Forget it. I’ll post an article. It’s not a white answer. It’s a more universal way (it supports string point operation and is more friendly to string errors, but sometimes undefined is better than reporting errors directly):
How to execute a function from its string name (execute function by name) in JavaScript | Our Code World

joyqi replied 4 months ago

I’ll delete it if I don’t add any more

joyqi replied 4 months ago

Please use the comment function

joyqi replied 4 months ago

Questions should be put in comments, not in answers.

joyqi replied 4 months ago

@fenYes, it is executed at the terminal

joyqi replied 4 months ago

Please ignore this clause

2 Answers
Xiao Ming answered 4 months ago

Just specify the object, the name of your example[fnName]()Change it like thiswindow[fnName]()You can run in a browser environment.
But if you want better compatibility, create an object yourself, like this:

<script>

var myproject = {}

myproject.aaa = function () {
  console.log('1')
}

var fnName = 'aaa'

myproject[fnName]() 

</script>
sandhiker answered 4 months ago

Square brackets are strings, but the calling object cannot be omitted. The function you define is under the window object in the browser, so you shouldwindow[fnName]()Call like this
The above answer is very careful. It is the safest to define an object without a window object.
If you want to delete the answer, the result will be deducted. Forget it. I’ll post an article. It’s not a white answer. It’s a more universal way (it supports string point operation and is more friendly to string errors, but sometimes undefined is better than reporting errors directly):
How to execute a function from its string name (execute function by name) in JavaScript | Our Code World