This question already has an answer here:
- Dynamic function name in javascript? 20 answers
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.
window.example = function () { alert('hello world') }
example();
or
name = 'example';
window[name] = function () { ... }
...
or
window[name] = new Function('alert("hello world")')
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"}
来源:https://stackoverflow.com/questions/14178430/javascript-dynamic-function-names