Dynamic function name in javascript?
As others mentioned, this is not the fastest nor most recommended solution. Marcosc's solution below is the way to go.
You can use eval:
var code = "this.f = function " + instance + "() {...}";
eval(code);
Dynamic function names in JavaScript
Updated answer in 2016:
The "However, that's changing..." part of the original answer below has changed. ES2015 ("ES6") was released a year ago, and JavaScript engines are now finally coming into compliance with one of its lesser-known aspects: Function#name
.
As of ES2015, this function has a name despite being created using an "anonymous" function expression:
var f = function() { };
Its name is f
. This is dictated by the specification (or the new one for ES2016) in dozens of different places (search for where SetFunctionName
is used). In this particular case, it's because it gets the name of the variable it's being assigned to. (I've used var
there instead of the new let
to avoid giving the impression that this is a feature of let
. It isn't. But as this is ES2015, I'll use let
from now on...)
Now, you may be thinking "That doesn't help me, because the f
is hardcoded," but stick with me.
This function also has the name f
:
let obj = {
f: function() { }
};
It gets the name of the property it's being assigned to (f
). And that's where another handy feature of ES2015 comes into effect: Computed property names in object initializers. Instead of giving the name f
literally, we can use a computed property name:
let functionName = "f";
let obj = {
[functionName]: function() { }
};
Computed property name syntax evaluates the expression in the []
and then uses the result as the property name. And since the function gets a true name from the property it's being assigned to, voilà, we can create a function with a runtime-determined name.
If we don't want the object for anything, we don't need to keep it:
let functionName = "f";
let f = ({
[functionName]: function() { }
})[functionName];
That creates the object with the function on it, then grabs the function from the object and throws the object away.
Of course, if you want to use lexical this
, it could be an arrow function instead:
let functionName = "f";
let f = ({
[functionName]: () => { }
})[functionName];
Here's an example, which works on Chrome 51 and later but not on many others yet:
// Get the namelet functionName = prompt( "What name for the function?", "func" + Math.floor(Math.random() * 10000));
// Create the functionlet f = ({ [functionName]: function() { }})[functionName];
// Check the nameif (f.name !== functionName) { console.log("This browser's JavaScript engine doesn't fully support ES2015 yet.");} else { console.log("The function's name is: " + f.name);}
How do I call a dynamically-named method in Javascript?
Assuming the populate_Colours
method is in the global namespace, you may use the following code, which exploits both that all object properties may be accessed as though the object were an associative array, and that all global objects are actually properties of the window
host object.
var method_name = "Colours";
var method_prefix = "populate_";
// Call function:
window[method_prefix + method_name](arg1, arg2);
How to call a function using a dynamic name in JS
Usually we should avoid eval. What you are trying to do is possible without using eval too and with a simpler code :
//variables
var ta = 3213;
var da = 44;
var s = [];
//Create string representation of function
s[1] = function test0(){ alert(" + da + "); };
s[0] = function test1(){ alert(" + ta +"); };
s.forEach((fun) => { this[fun.name] = fun;});
// calling the function
this["test"+1]();
Or simple in your code do :
this["test"+1]();
EDIT:
If you are using string and eval just because you are getting function name as string, instead you can create an object :
var data = {};
for(var i = 0; i<10; i++) {
data['key'+ i] = function (i) { alert(i); }.bind(null, i);
}
Javascript: Dynamic function names
window.example = function () { alert('hello world') }
example();
or
name = 'example';
window[name] = function () { ... }
...
or
window[name] = new Function('alert("hello world")')
TypeScript: auto-generated dynamic function names
Edit for 4.1
Using Template literal types and mapped type 'as' clauses we can now do concatenate strings in the type system and create a class that has these properties created dynamically.
function defineDynamicClass<T extends string[]>(...info: T): {
new (): {
[K in T[number] as `get${Capitalize<K>}`]: () => unknown
} & {
[K in T[number] as `set${Capitalize<K>}`]: (value: unknown) => void
} & {
info: T
}
} {
return class {
get info () {
return info;
}
} as any
}
class MyClass extends defineDynamicClass('A', 'B', 'ABAB') {
}
let s =new MyClass();
s.getA();
s.getABAB();
s.setA("")
s.info;
Playground Link
Before 4.1
The within language approach
There is no way to do this within the type system, since we can't perform string manipulation on string literal types. The closest you can get, without external tools, is to create get/set
methods that take a string literal type, that will be of the same as that returned by the getInfo
method.
function stringLiteralArray<T extends string>(...v: T[]){ return v;}
abstract class Original {
get(name: this['info'][number]) {
return null;
}
set(name: this['info'][number], value: any) {
return null;
}
get info() : string[]{
return [];
}
}
class MyOtherClass extends Original {
get info() {
return stringLiteralArray('A', 'B', 'ABAB');
}
}
class MyClass extends Original {
get info() {
return stringLiteralArray('C', 'D', 'DEDE');
}
}
let s =new MyClass();
s.get('A') // error
s.get('C') // ok
While this approach is not 100% what you want, form our previous discussions the aim was to have full code-completion for the methods, and this approach achieves this. You get errors if you pass in the wrong value and you get a completion list for the string:
The compiler API approach
A second approach would be to create a custom tool that uses the typescript compiler API to parse the ts files, look for classes derived from Original
and generates interfaces containing the methods (either in the same file or a different file) , if you are interested in this I can write the code, but it's not trivial, and while the compiler API is stable I don't think the compiler team takes as much care with backward compatibility as they do with the language (in fact this is the exact statement they make in the documentation page).
If you are interested in such a solution, let me know and I can provide it, but I advise against it.
Calling functions as dynamic function as array values in javascript
Use function names rather than using strings
function getId(arr) { for (let i in arr) { console.log("Function getId " + arr[i]); }}
function getMarker(arr) { for (let i in arr) { console.log("Function getMarker " + arr[i]); }}const PAGEAPP = { processes: [getId, getMarker], init: () => { for (let foo of PAGEAPP.processes) { foo([1, 2, 3]);
} },}
PAGEAPP.init()
How to create Dynamic Function Name in ReactJS & use on onBlur?
You can have a generic function like this, which takes type as input and returns a validating function.
const createValidator = type => {
switch (type) {
case 'email':
return (event) => {
const email = event.target.value;
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
(!re.test(email)) && console.log("Please enter a valid email address");
}
default:
return null;
}
}
And in your input tag, you can use it like this
<input onChange={handleChange} onBlur={createValidator('email')} />
Related Topics
Load Jquery with JavaScript and Use Jquery
Preventdefault() on an <A> Tag
JavaScript Print Iframe Contents Only
How to Dynamically Insert a <Script> Tag via Jquery After Page Load
Escaping Strings in JavaScript
How to Use React Hooks in React Classic 'Class' Component
JSON.Stringify Doesn't Work with Normal JavaScript Array
How to Destructure Object Properties with Key Names That Are Invalid Variable Names
Onclick Function Runs Automatically
New Es6 Syntax for Importing Commonjs/Amd Modules I.E. 'Import Foo = Require('Foo')'
Differencebetween JavaScript Promises and Async Await
Make Browser Window Blink in Task Bar
Unexpected Behavior Using Array Map on an Array Initialized with Array Fill
How to Remove All the Options of a Select Box and Then Add One Option and Select It with Jquery
Generating Non-Repeating Random Numbers in Js
Is JavaScript an Untyped Language
Get the Index of the Object Inside an Array, Matching a Condition