1

can you use template literals to name functions dynamically

let variable = "something"

function `constant${variable}` () {
               //do something
}
jeff
  • 87
  • 1
  • 11
  • 2
    SyntaxError: Unexpected template string – Tinu Jos K Feb 18 '20 at 10:41
  • Does this answer your question? [Is there any non-eval way to create a function with a runtime-determined name?](https://stackoverflow.com/questions/9479046/is-there-any-non-eval-way-to-create-a-function-with-a-runtime-determined-name) – Jacob Feb 18 '20 at 10:41
  • I know, but is there a hack way to do this somehow? – jeff Feb 18 '20 at 10:42
  • @Ivar. That is how to call it. OP wants to create it. – Jacob Feb 18 '20 at 10:44
  • 1
    What is this for? What are you trying to build. With this approach you first need a hack to create the function and then you'll need another hack to use it. I'm almost certain that there's a better way – Thomas Feb 18 '20 at 10:54

4 Answers4

1

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()
ahmet dundar
  • 92
  • 1
  • 5
1

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()
Raja Jaganathan
  • 33,099
  • 4
  • 30
  • 33
1

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();
Peter B
  • 22,460
  • 5
  • 32
  • 69
1

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()
Dawood Valeed
  • 155
  • 1
  • 3