14

How to create a function with a dynamic name? Something like:

function create_function(name){
   new Function(name, 'console.log("hello world")');
}
create_function('example');
example(); // --> 'hello world'

Also the function should be a Function Object so I can modify the prototype of the object.

J. Mini
  • 1,868
  • 1
  • 9
  • 38
Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
  • Could you explain what problem you are trying to solve? – Philipp Jan 06 '13 at 01:44
  • @Philipp: For instance, OP may be interested in replacing some constructor with another one, but giving it the same name as the original constructor, so code sees the same function name. That may be one of the reasons that I'm facing. But I'm sure there are others. – Robert Koritnik Jan 08 '15 at 23:54

2 Answers2

14

I've been playing around with this for the last 3 hours and finally got it at least somewhat elegant using new Function as suggested on other threads:

/**
 * JavaScript Rename Function
 * @author Nate Ferrero
 * @license Public Domain
 * @date Apr 5th, 2014
 */
var renameFunction = function (name, fn) {
    return (new Function("return function (call) { return function " + name +
        " () { return call(this, arguments) }; };")())(Function.apply.bind(fn));
};   

/**
 * Test Code
 */
var cls = renameFunction('Book', function (title) {
    this.title = title;
});

new cls('One Flew to Kill a Mockingbird');

If you run the above code, you should see the following output to your console:

Book {title: "One Flew to Kill a Mockingbird"}
Nate Ferrero
  • 1,408
  • 14
  • 15
13
window.example = function () { alert('hello world') }
example();

or

name = 'example';
window[name] = function () { ... }
...

or

window[name] = new Function('alert("hello world")')
akonsu
  • 28,824
  • 33
  • 119
  • 194
  • [Add a fiddle](http://jsfiddle.net/mE2n5/) in your answer. – The Alpha Jan 06 '13 at 01:46
  • 11
    I do not know why the wrong answer is a hign rank. the author need a named function at runtime, not a global name to visit. – Riceball LEE Feb 02 '15 at 00:52
  • the below post is better way to do or this one? – Ehsan Sajjad May 18 '15 at 06:18
  • @EhsanSajjad my response and that by ConnorBlack are the same. the difference is that he stores the function object in a variable, and I store it in a `window` object, just to demonstrate that if you use `window` you can access the function everywhere. – akonsu Jun 30 '15 at 18:07
  • I prefer the answer below as it doesn't pollute the global scope. – TomDotTom Jul 24 '15 at 10:23
  • My own problem was similar (Does JS do dynamic function names?) - and solved by using an array index as the function name eg foo[dynFuncName](). Thx. – Richard Dec 29 '15 at 15:51