I have this:
this.f = function instance(){};
I would like to have this:
this.f = function ["instance:" + a](){};
The dynamic nature of JavaScript means that a function is able to not only call itself, but define itself, and even redefine itself. This is done by assigning an anonymous function to a variable that has the same name as the function.
To use dynamic function name in JavaScript, we can create an object with the function name. const name = "myFn"; const fn = { [name]() {} }[name]; to set the fn variable to a function with the name name . We put the name method in the object and then we get the method with [name] .
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.
This will basically do it at the most simple level:
"use strict"; var name = "foo"; var func = new Function( "return function " + name + "(){ alert('sweet!')}" )(); //call it, to test it func();
If you want to get more fancy, I have a written an article on "Dynamic function names in JavaScript".
You can use Object.defineProperty as noted in the MDN JavaScript Reference:
var myName = "myName"; var f = function () { return true; }; Object.defineProperty(f, 'name', {value: myName, writable: false});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With