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.
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"}
window.example = function () { alert('hello world') }
example();
or
name = 'example';
window[name] = function () { ... }
...
or
window[name] = new Function('alert("hello world")')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With