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
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
I’ll delete it if I don’t add any more
Please use the comment function
Questions should be put in comments, not in answers.
@fenYes, it is executed at the terminal
Please ignore this clause