Để thực thi function khi tên là string, truy cập method bằng bracket notation obj['methodName']() hoặc window['funcName']() cho global function.
Ví dụ
<html>
<body>
<script>
class Demo {
methodOne() {
document.write("50");
}
methodTwo() {
this['methodOne'](); // Gọi methodOne qua string name
document.write("<br> 100");
}
}
let num = new Demo();
num['methodTwo'](); // Gọi methodTwo qua string name
</script>
</body>
</html>
Các cách gọi function từ string
1. Object/Class Method (Bracket Notation)
const obj = {
greet() { console.log('Hello'); },
farewell() { console.log('Bye'); }
};
const methodName = 'greet';
obj[methodName](); // "Hello"
2. Global Function (Window Object)
function sayHi() { console.log('Hi'); }
window['sayHi'](); // "Hi"
// Hoặc (non-strict mode)
this['sayHi']();
3. Module/Object Map (Best Practice)
// Định nghĩa map actions
const actions = {
save: () => console.log('Saving...'),
delete: () => console.log('Deleting...'),
export: () => console.log('Exporting...')
};
// Dispatch an toàn
function dispatch(actionName) {
const action = actions[actionName];
if (typeof action === 'function') {
action();
} else {
console.warn('Unknown action:', actionName);
}
}
dispatch('save'); // "Saving..."
dispatch('invalid'); // Warning
4. eval() - KHÔNG KHUYẾN NGHỊ
// Nguy hiểm: XSS, performance, debugging khó
eval('sayHi()');
Use Case thực tế
- Event system:
emitter.on('event', handlers[eventName]). - Router:
routes[path](). - Command pattern:
commands[cmd](). - Plugin system: dynamic load & execute.
Best Practice
- Dùng Object Map / Map thay vì global namespace.
- Validate function name trước khi gọi (allowlist).
- Tránh
eval(),new Function()với user input. - TypeScript:
Recordcho type safety.void>