Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function starting only with the function name as a string (ES6 syntax)

I'm doing a weird thing where I get the name of a function, and call the function with that name, like this:

function myFunc(){
    //do somethng
};
var myFuncName = 'myFunc';
window[myFuncName](); // Expected result.

...which works, but now I've defined the func using ES6 const naming, window[myFuncName] is undefined:

const myFunc = () => {
    //do somethng
};
var myFuncName = 'myFunc';
window[myFuncName](); // window[myFuncName] is not a function.

Does anyone know how to call an ES6 function when you have only it's name as a string? I'm working in a browser Web Extension but think this is a general JavaScript problem. Thanks!

like image 917
tripRev Avatar asked Dec 29 '25 11:12

tripRev


1 Answers

It'd only be possible with eval, which shouldn't be used:

eval(myFuncName + '()');

Instead, change your code so that the function is put onto an object (even if it's not the window), then use ordinary bracket notation to look up the property value (just like you're doing with window, except with fns instead), and call the retrieved function:

const fns = {
  myFunc() {
    console.log('do something');
  }
};
const myFuncName = 'myFunc';
fns[myFuncName]();

If you want to more closely imitate const for the property on the object, use Object.defineProperty to make sure the function property can't be deleted nor reassigned, via configurable: false:

'use strict';
const fns = {};
Object.defineProperty(fns, 'myFunc', {
  configurable: false,
  value: () => {
    console.log('do something');
  }
});
const myFuncName = 'myFunc';
fns[myFuncName]();

// can't reassign property:
fns.myFunc = 'foo';
like image 115
CertainPerformance Avatar answered Dec 31 '25 00:12

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!