can you use template literals to name functions dynamically
let variable = "something"
function `constant${variable}` () {
//do something
}
can you use template literals to name functions dynamically
let variable = "something"
function `constant${variable}` () {
//do something
}
The correct way to achieve is below your original code shouldnt work because you are trying to put string where variable name expected.
PS. By using this instead of window or global you can use snippet in both browser and node.js
let variable = "something"
this[ `constant${variable}`]= ()=> {
console.log("it works");
}
constantsomething()
You can try like below, we can use window
or separate object
to create a dynamic function using template literal
let variable = "something"
window[`constant${variable}`] = function () {
console.log('dynamic func')
}
(or)
let variable = "something"
var obj = {
[`constant${variable}`]: function () {
console.log('dynamic func')
}
}
obj.constantsomething()
Not like that, because a template literal evaluates to a string, and you can't write function "abc"() { ... }
either.
However, you can try putting it in global context using the name + bracket notation. E.g. when running in a browser:
let variable = "something"
window[`constant${variable}`] = function() {
console.log("Hello!");
}
constantsomething();
And with a Node project, it will probably go something like this:
let variable = "something"
global[`constant${variable}`] = function() {
console.log("Hello!");
}
constantsomething();
You can declare a variable and fetch its context using this
keyword to declare your function
Example
let fnName = "CoolDynamicFunction";
this[`${fnName}`] = () => {
console.log("I'm a cool dynamic function")
}
and then call it using
CoolDynamicFunction()