Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
Is there a way to access a defined function by adding its name in the form of a string and executing it later?

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 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();
}
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda