Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Dynamic function names [duplicate]

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.

like image 651
Adam Halasz Avatar asked Jan 06 '13 01:01

Adam Halasz


2 Answers

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"}
like image 104
Nate Ferrero Avatar answered Oct 21 '22 22:10

Nate Ferrero


window.example = function () { alert('hello world') }
example();

or

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

or

window[name] = new Function('alert("hello world")')
like image 13
akonsu Avatar answered Oct 21 '22 22:10

akonsu