Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic function name in javascript?

I have this:

this.f = function instance(){}; 

I would like to have this:

this.f = function ["instance:" + a](){}; 
like image 281
Totty.js Avatar asked May 06 '11 00:05

Totty.js


People also ask

What is a dynamic function in JavaScript?

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.

How do you call a dynamic function name?

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] .

How do you name a function in JavaScript?

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, ...)

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.


2 Answers

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".

like image 195
Marcosc Avatar answered Oct 14 '22 09:10

Marcosc


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}); 
like image 43
Darren Avatar answered Oct 14 '22 08:10

Darren