Quantcast
Channel: How to execute a JavaScript function when I have its name as a string - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by snnsnn for How to execute a JavaScript function when I have its name as a string

$
0
0

I don't think you need complicated intermediate functions or eval or be dependent on global variables like window:

function fun1(arg) {  console.log(arg);}function fun2(arg) {  console.log(arg);}const operations = {  fun1,  fun2};operations["fun1"]("Hello World");operations.fun2("Hello World");// You can use intermediate variables, if you likelet temp = "fun1";operations[temp]("Hello World");

It will also work with imported functions:

// mode.jsexport function fun1(arg) {  console.log(arg);}export function fun2(arg) {  console.log(arg);}
// index.jsimport { fun1, fun2 } from "./mod";const operations = {  fun1,  fun2};operations["fun1"]("Hello World");operations["fun2"]("Hello World");

Since it is using property access, it will survive minimization or obfuscation, contrary to some answers you will find here.


Viewing all articles
Browse latest Browse all 38

Latest Images

Trending Articles



Latest Images