I have an object that contains many functions
var obj = {
'Func1': function() {},
'Func2': function() {},
'Func3': function() {},
'Func4': function() {}
...
}
var functionToCall = 'Func2';
I want to dynamically call a function inside the object using a string value. Any idea how to achieve this in JavaScript?
只需使用[]
查找对象的属性,然后使用()
调用函数
obj[functionToCall]();
您可以通过[]
访问对象的属性:
obj['Func2']();
This is all there's to it :
var obj = { 'Func1': function() { alert('Func1') }, 'Func2': function() { alert('Func2') }, 'Func3': function() { alert('Func3') }, 'Func4': function() { alert('Func4') } } var functionToCall = 'Func2'; obj[functionToCall]();
(see also this Fiddle )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.