[removed] Dynamic function names [duplicate]

2019-01-18 21:32发布

This question already has an answer here:

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.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-18 22:22

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"}
查看更多
【Aperson】
3楼-- · 2019-01-18 22:24
window.example = function () { alert('hello world') }
example();

or

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

or

window[name] = new Function('alert("hello world")')
查看更多
登录 后发表回答