首页 > 解决方案 > How to call a function using variable in javascript without using window?

问题描述

Suppose there is a function (from a module) named fiveStar and I want to call it using a variable,

For e.g using window, I could do this:

const num = 'five';
const functionName = `${num}Star';
window[functionName]();

Is there any other way I could do this without using window?

标签: javascriptfunctionvariables

解决方案


You could use an object to group functions together.

const myModule = {
   fiveStar: ()=>{}
   //other methods...
};
const num = 'five';
const functionName = `${num}Star`;
myModule[functionName]();

推荐阅读