Home > front end >  Is there a way to access a defined function by adding its name in the form of a string and executing
Is there a way to access a defined function by adding its name in the form of a string and executing

Time:07-31

I know that functions are objects, and objects never equal each other, even if they are identical. The question that I have is that, let's say I have a function as follows:

const xyz = () => a   b;

Can I access this function somehow using this code below or something similar:

const func = `x   y   z`;

And then later execute it like a normal function? Is there a library or tool that I can use?

func()

I am using Javascript. I tried googling about it but couldn't make Google understand. Please, if the question is stupid, don't downvote it. Stackoverflow says they will ban me. Just let me know and I will delete this question.

I am building a small project and am importing functions from a file where they are already defined. I want those functions to run when a user clicks a specific button. The text of the button plus an additional string can be joined to make the name of that fucntion. Now I want to run that function using the name but it ends up in error. Here is the code of what I am trying to do.

import "./style.css";
import tabs from "./tab.js";
import {biryaniTabChange, pulaoTabChange} from "./dishTexts.js";


tabs.heading();
tabs.createTab();
tabs.appendDish("Biryani");
tabs.appendDish("Pulao");
tabs.appendDish("Aloo Matar");
tabs.dishDiv();
let dishes = document.querySelectorAll(".dishes");
document.addEventListener('click', (e) => {
    if (!e.target.classList.contains('dishes')) return;
    if (!e.target.closest('div').classList.contains('tabs')) return;
    let func = new Function(e.target.textContent.toLowerCase().replace(/\s /g, '')   "TabChange");
    console.log(func);
    e.target.addEventListener('click', func())
})
window.onload = () => {
    biryaniTabChange();
}

CodePudding user response:

First import every function into one namespace object:

import * as fns from "./dishTexts.js";

Then you can access them by name with the string:

const name = 'biryaniTabChange'
fns[name]()

or just

fns['biryaniTabChange']()

And your final code will look something like this:

const name = e.target.textContent.toLowerCase().replace(/\s /g, '')   "TabChange"
const func = fns[name]
e.target.addEventListener('click', func) // no call here!

Based on the sample you provided

  • Related