Javascript:动态函数名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14178430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:56:27  来源:igfitidea点击:

Javascript: Dynamic function names

javascriptfunctiondynamicnames

提问by Adam

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.

该函数也应该是一个函数对象,这样我就可以修改对象的原型。

采纳答案by akonsu

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

or

或者

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

or

或者

window[name] = new Function('alert("hello world")')

回答by Nate Ferrero

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:

在过去的 3 个小时里,我一直在玩这个,最后按照其他线程的建议使用 new Function 至少有点优雅:

/**
 * 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"}