Specifically when used within objects, when would a getter function be used over a regular function. For example, what is the difference between using
const obj = {
get method() {
return data;
}
};
console.log(obj.method);
and this
conts obj = {
method() {
return data;
}
};
console.log(obj.method());
1 . With a normal property/method, you can change its value.
A getter method cannot have its value changed. Look what happens when we try to change the getter here (it doesn't change):
const obj = {
methodNormal() {
return 5;
},
get methodGetter() {
return 5;
}
};
obj.methodNormal = "red";
obj.methodGetter = "blue";
console.log(obj);
2 . Secondly, with a normal property you have the luxury of either returning the function i.e. obj.methodNormal or returning the function executing i.e. obj.methodNormal(). With getter functions you do not have the luxury of returning the function. You can only do obj.methodGetter which executes that function. The code snippet below demonstrates that.
const obj = {
methodNormal() {
return 5;
},
get methodGetter() {
return 5;
}
};
let captureNormalMethod = obj.methodNormal;
let captureGetterMethod = obj.methodGetter;
console.log(captureNormalMethod);
console.log(captureGetterMethod);
Both these qualities - being unchangeable & unable to be captured in a new variable or property - contribute to getter functions having a sense of 'hiddenness'. Now you can understand what people mean when they say getters are 'read-only' properties!
Further reading:
What I've been referring to as 'normal properties' are called data properties (good article).
Getter methods are an example of what are called accessor properties (good article).
A method can only return data a property can also have a setter
This is useful if you want to expose read-only properties. It isn't just a function to the caller.
In your example, both do the same thing, but the importance is not how they are alike but how they are not. You can, for example, pass the method version as an argument somewhere else to do some lazy execution, but the getter won't work like that.
const obj = {
lazyProp(parameter) {
return parameter + 2;
}
}
function evaluateLazy(fn) {
return fn()
}
evaluateLazy(obj.lazyProp)
One useful scenario is where you want to use regular property access on all your properties, but need to invoke a method to calculate a given value. For example take the following example which doesn't use a getter. It ends up printing the function, not the return value of the function. Without a getter, we would need to handle a specific case where the value is a function, and then invoke it.
const obj = {
x: 10,
y: 20,
total() {
return this.x + this.y;
}
}
const prettyPrintObj = obj => {
for(let key in obj) {
console.log(`${key.toUpperCase()} is ${obj[key]}`);
}
}
prettyPrintObj(obj);
However, with a getter, we can use the same function, and don't need to handle specific cases for where obj[key] is a function, as simply doing obj[key] on a getter will invoke the function for you:
const obj = {
x: 10,
y: 20,
get total() {
return this.x + this.y;
}
}
const prettyPrintObj = obj => {
for(let key in obj) {
console.log(`${key.toUpperCase()} is ${obj[key]}`);
}
}
prettyPrintObj(obj);
I realize my question's title may be worded weirdly, so I apologize up front.
To be clear, I am referring to this:
var IIFE = (function () {
var a = Symbol("a");
function IIFE() {
this["a"] = null;
}
IIFE.prototype = {
get a() { return this[a]; },
set a(n) { this[a] = n; }
}
return IIFE;
}());
var iife = new IIFE;
I want to dynamically add 'b' & 'c' using an array:
var arrProps = ['b','c'];
to an instance of IIFE. I don't care how it gets done, so as long as the values specified within arrProps can be accessed & assigned the same as you would with 'a' inside the instance, outside the instance, and within prototype get/set. An example of using 'b' would be:
inside the instance: this["b"] = value;
outside of the instance: iife.b = value;
prototype set/get: this[b] = value;
As far as the get/set internals go, there is nothing more than just getting the value and setting value.
Any help would be very much appreciated.
Instead of using a Symbol, have the function return a Proxy instead, and you can use its get and set traps to check for accesses/assignments to arbitrary properties:
const proxy = new Proxy({}, {
get(obj, prop) {
console.log('getting');
return obj[prop];
},
set(obj, prop, newVal) {
console.log('setting');
return obj[prop] = newVal;
},
});
proxy.a = 'aVal';
console.log(proxy.a);
proxy.b= 'bVal';
proxy.c = 'cVal';
proxy.a = 'anotherAVal';
I currently have a Proxy object that I want to capture property calls to if the property is not defined.
A basic version of my code would be something like this.
var a = new Proxy({}, {
get: function(target, name, receiver) {
if (target in name) {
return target[name];
} else {
function a() {
return arguments;
}
var args = a();
return [target, name, receiver, args];
}
}
});
Property calls to a here (i.e: a.b; a.c() etc) should return the target, name, receiver and arguments of the property call.
The problem I wish to solve, however, requires me to know whether the property call is for a property or a function, such that I can apply different treatments to each. Checking the length of the arguments object does not work, as calling a.c() would yield a length of 0 just like a.b, so it would be treated as a plain property and not a method.
Is there a way, therefore, to identify whether the property attempting to be accessed is being called as a function or not.
UPDATE: I should clarify, this method needs to work if the accessed property/method is undefined, as well as existing.
It's possible in a very hacky way. We return a function if the property is undefined. If this function is called, then we know the user was trying to call the property as a function. If it never is, it was called as a property. To check if the function was called, we take advantage of the fact that a Promise's callback is called in the next iteration of the event loop. This means that we won't know if it's a property or not until later, as the user needs a chance to call the function first (as our code is a getter).
One drawback of this method is that the value returned from the object will be the new function, not undefined, if the user was expecting a property. Also this won't work for you if you need the result right away and can't wait until the next event loop iteration.
const obj = {
func: undefined,
realFunc: () => "Real Func Called",
prop: undefined,
realProp: true
};
const handlers = {
get: (target, name) => {
const prop = target[name];
if (prop != null) { return prop; }
let isProp = true;
Promise.resolve().then(() => {
if (isProp) {
console.log(`Undefined ${name} is Prop`)
} else {
console.log(`Undefined ${name} is Func`);
}
});
return new Proxy(()=>{}, {
get: handlers.get,
apply: () => {
isProp = false;
return new Proxy(()=>{}, handlers);
}
});
}
};
const proxied = new Proxy(obj, handlers);
let res = proxied.func();
res = proxied.func;
res = proxied.prop;
res = proxied.realFunc();
console.log(`realFunc: ${res}`);
res = proxied.realProp;
console.log(`realProp: ${res}`);
proxied.propC1.funcC2().propC3.funcC4().funcC5();
Would the typeof operator work for you?
For example:
if(typeof(a) === "function")
{
...
}
else
{
...
}
You can't know ahead of time whether it's a call expression or just a member expression, but you can deal with both situations simultaneously.
By returning a proxy targeting a deep clone of the original property that reflects all but two trap handlers to the original property, you can either chain or invoke each member expression.
The catch is that the proxy target also needs to be callable so that the handler.apply trap does not throw a TypeError:
function watch(value, name) {
// create handler for proxy
const handler = new Proxy({
apply (target, thisArg, argsList) {
// something was invoked, so return custom array
return [value, name, receiver, argsList];
},
get (target, property) {
// a property was accessed, so wrap it in a proxy if possible
const {
writable,
configurable
} = Object.getOwnPropertyDescriptor(target, property) || { configurable: true };
return writable || configurable
? watch(value === object ? value[property] : undefined, property)
: target[property];
}
}, {
get (handler, trap) {
if (trap in handler) {
return handler[trap];
}
// reflect intercepted traps as if operating on original value
return (target, ...args) => Reflect[trap].call(handler, value, ...args);
}
});
// coerce to object if value is primitive
const object = Object(value);
// create callable target without any own properties
const target = () => {};
delete target.length;
delete target.name;
// set target to deep clone of object
Object.setPrototypeOf(
Object.defineProperties(target, Object.getOwnPropertyDescriptors(object)),
Object.getPrototypeOf(object)
);
// create proxy of target
const receiver = new Proxy(target, handler);
return receiver;
}
var a = watch({ b: { c: 'string' }, d: 5 }, 'a');
console.log(a('foo', 'bar'));
console.log(a.b());
console.log(a.b.c());
console.log(a.d('hello', 'world'));
console.log(a.f());
console.log(a.f.test());
Open Developer Tools to view Console.
The Stack Snippets Console attempts to stringify the receiver in a weird way that throws a TypeError, but in the native console and Node.js it works fine.
Try it online!
Some ideas I've come up with, which achieve a similar result at a small cost:
A
typeof(a.b) === "function" //`false`, don't call it.
typeof(a.c) === "function" //`true`, call it.
//Maybe you're not intending to try to call non-functions anyways?
a.c();
B
get: function(target, property) {
//For this, it would have to already be set to a function.
if (typeof(target[property] === "function") {
}
}
C
a.b;
//Simply change the structuring a little bit for functions, e.g.:
a.func.c();
//Then, `func` would be set and handled as a special property.
I need to initialize some kind of a prototype on already existing jQuery elements collection. The main problem is that the prototype should be accessible only inside of that collection and on elements produced by built-in jQuery functions like .find() on that collection or on some children objects inside of that collection, for example:
var $a = $('a');
$a.__proto__.foo/*some magic over here*/ = function(){ alert('foo!'); };
$a.foo(); //should show alert('foo!')
$a.find('b').foo(); //should produce the same action
$('a').foo(); //should produce an error (method not found)
If using $a.__proto__ like in example above, the jQuery.prototype is accessed, so all the new elements in outside of that jQuery-collection (for example, $('a')) are granting an access to .foo() method. That behaviour is unacceptable on a problem statement.
Is that actually possible?
Okay, here's the thing, I have a rather complex ES6 solution, so I won't be able to explain it in great depth, but if you have some particular questions, go ahead.
var wrap = (function wrapper() {
var store = {};
function wrap(fn) {
return new Proxy(fn, {
apply(target, thisArg, argumentsList) {
var result = Reflect.apply(target, thisArg, argumentsList);
// `jQuery(...)` returns a "rich" object that always contain `.length`
if (result.length > 0) {
result = new Proxy(result, {
get(target, propertyKey, receiver) {
var value = Reflect.get(target, propertyKey, receiver);
if (Object.keys(store).includes(propertyKey)) {
value = store[propertyKey];
}
return value;
},
set(target, propertyKey, value, receiver) {
// TODO: use `Reflect.set(), somehow`
// return Reflect.set(store, propertyKey, value, receiver);
return (store[propertyKey] = value);
},
});
}
return result;
}
});
}
return wrap;
})();
var $ = wrap(jQuery);
$.prototype.find = wrap(jQuery.prototype.find); // TODO: implement recursively in `wrap()`
var x = $('div');
var xx = x.find('div');
var xxx = x.find('divvv');
xx.foo = 123;
console.log(x.foo); // 123
console.log(xx.foo); // 123
console.log(xxx.foo); // undefined
I have this:
this.f = function instance(){};
I would like to have this:
this.f = function ["instance:" + a](){};
This will basically do it at the most simple level:
"use strict";
var name = "foo";
var func = new Function(
"return function " + name + "(){ alert('sweet!')}"
)();
//call it, to test it
func();
If you want to get more fancy, I have a written an article on "Dynamic function names in JavaScript".
You can use Object.defineProperty as noted in the MDN JavaScript Reference:
var myName = "myName";
var f = function () { return true; };
Object.defineProperty(f, 'name', {value: myName, writable: false});
In recent engines, you can do
function nameFunction(name, body) {
return {[name](...args) {return body.apply(this, args)}}[name]
}
const x = nameFunction("wonderful function", (p) => p*2)
console.log(x(9)) // => 18
console.log(x.name) // => "wonderful function"
Thanks to T S for pointing out the need to preserve this in the comments.
Also, these days, I'd probably use the Object.defineProperty approach to achieve something similar.
Update 2021: CherryDT's answer should be the easiest most straight forward way now, but it doesn't work consistently with different browsers for stack traces or Function.prototype.toString(), so if you need that you're stuck with this less convenient solution.
Old answer: Many suggestions here are suboptimal, by using eval, hacky solutions or wrappers.
As of ES2015 names are inferred from the syntactic position for variables and properties.
So this will work just fine:
const name = 'myFn';
const fn = {[name]: function() {}}[name];
fn.name // 'myFn'
Resist the temptation to create named function factory methods as you wouldn't be able to pass the function from outside and retrofit it into the syntactic position to infer its name. Then it's already too late. If you really need that, you have to create a wrapper. Someone did that here, but that solution doesn't work for classes (which are also functions).
A much more in-depth answer with all the variants outlined has been written here: https://stackoverflow.com/a/9479081/633921
As others mentioned, this is not the fastest nor most recommended solution. Marcosc's solution below is the way to go.
You can use eval:
var code = "this.f = function " + instance + "() {...}";
eval(code);
What about
this.f = window["instance:" + a] = function(){};
The only drawback is that the function in its toSource method wouldn't indicate a name. That's usually only a problem for debuggers.
The syntax function[i](){} implies an object with property values that are functions, function[], indexed by the name, [i].
Thus
{"f:1":function(){}, "f:2":function(){}, "f:A":function(){}, ... } ["f:"+i].
{"f:1":function f1(){}, "f:2":function f2(){}, "f:A":function fA(){}} ["f:"+i] will preserve function name identification. See notes below regarding :.
So,
javascript: alert(
new function(a){
this.f={"instance:1":function(){}, "instance:A":function(){}} ["instance:"+a]
}("A") . toSource()
);
displays ({f:(function () {})}) in FireFox.
(This is almost the same idea as this solution, only it uses a generic object and no longer directly populates the window object with the functions.)
This method explicitly populates the environment with instance:x.
javascript: alert(
new function(a){
this.f=eval("instance:"+a+"="+function(){})
}("A") . toSource()
);
alert(eval("instance:A"));
displays
({f:(function () {})})
and
function () {
}
Though the property function f references an anonymous function and not instance:x, this method avoids several problems with this solution.
javascript: alert(
new function(a){
eval("this.f=function instance"+a+"(){}")
}("A") . toSource()
);
alert(instanceA); /* is undefined outside the object context */
displays only
({f:(function instanceA() {})})
The embedded : makes the javascript function instance:a(){} invalid.
Instead of a reference, the function's actual text definition is parsed and interpreted by eval.
The following is not necessarily problematic,
The instanceA function is not directly available for use as instanceA()
and so is much more consistent with the original problem context.
Given these considerations,
this.f = {"instance:1": function instance1(){},
"instance:2": function instance2(){},
"instance:A": function instanceA(){},
"instance:Z": function instanceZ(){}
} [ "instance:" + a ]
maintains the global computing environment with the semantics and syntax of the OP example as much as possible.
The most voted answer has got already defined [String] function body. I was looking for the solution to rename already declared function's name and finally after an hour of struggling I've dealt with it. It:
takes the alredy declared function
parses it to [String] with .toString() method
then overwrites the name (of named function) or appends the new one (when anonymous) between function and (
then creates the new renamed function with new Function() constructor
function nameAppender(name,fun){
const reg = /^(function)(?:\s*|\s+([A-Za-z0-9_$]+)\s*)(\()/;
return (new Function(`return ${fun.toString().replace(reg,`$1 ${name}$3`)}`))();
}
//WORK FOR ALREADY NAMED FUNCTIONS:
function hello(name){
console.log('hello ' + name);
}
//rename the 'hello' function
var greeting = nameAppender('Greeting', hello);
console.log(greeting); //function Greeting(name){...}
//WORK FOR ANONYMOUS FUNCTIONS:
//give the name for the anonymous function
var count = nameAppender('Count',function(x,y){
this.x = x;
this.y = y;
this.area = x*y;
});
console.log(count); //function Count(x,y){...}
For setting the name of an existing anonymous function:
(Based on #Marcosc's answer)
var anonymous = function() { return true; }
var name = 'someName';
var strFn = anonymous.toString().replace('function ', 'return function ' + name);
var fn = new Function(strFn)();
console.log(fn()); // —> true
Demo.
Note: Don't do it ;/
The function's name property by default isn't writeable, but since it's configurable we can still use Object.defineProperty to change it. Since Object.defineProperty conveniently returns the object itself, we can write a function with a dynamic name like this:
const theName = 'foobar'
const fn = Object.defineProperty(function () {
/* ... */
}, 'name', { value: theName })
console.log(fn.name) // Logs foobar
Of course this could be factored out into a helper function:
const nameFunction = (name, fn) => Object.defineProperty(fn, 'name', { value: name })
const fn = nameFunction('foobar', function () {
/* ... */
})
console.log(fn.name) // Logs foobar
The above nameFunction function can also be used to rename an existing function, of course (here it's just renaming and returning the anonymous one).
Dynamic methods of an object may be created using Object Literal Extensions provided by ECMAScript 2015 (ES6):
const postfixes = ['foo', 'bar'];
const mainObj = {};
const makeDynamic = (postfix) => {
const newMethodName = 'instance: ' + postfix;
const tempObj = {
[newMethodName]() {
console.log(`called method ${newMethodName}`);
}
}
Object.assign(mainObj, tempObj);
return mainObj[newMethodName]();
}
const processPostfixes = (postfixes) => {
for (const postfix of postfixes) {
makeDynamic(postfix);
}
};
processPostfixes(postfixes);
console.log(mainObj);
The output of running the code above is:
"called method instance: foo"
"called method instance: bar"
Object {
"instance: bar": [Function anonymous],
"instance: foo": [Function anonymous]
}
the best way it is create object with list of dynamic functions like:
const USER = 'user';
const userModule = {
[USER + 'Action'] : function () { ... },
[USER + 'OnClickHandler'] : function () { ... },
[USER + 'OnCreateHook'] : function () { ... },
}
There are two methods to achieve this, and they have their pros and cons.
name property definition
Defining immutable name property of a function.
Pros
Every character is available for the name. (eg. () 全 {}/1/얏호/ :D #GO(#*#%! /*)
Cons
The function's syntactic (“expressional”) name may not correspond with its name property value.
Function expression evaluation
Making a named function expression and evaluating it with Function constructor.
Pros
The function's syntactic (“expressional”) name always corresponds with its name property value.
Cons
Whitespaces (and etc.) are not available for the name.
Expression-injectable (eg. For input (){}/1//, the expression is return function (){}/1//() {}, gives NaN instead of a function.).
const demoeval = expr => (new Function(`return ${expr}`))();
// `name` property definition
const method1 = func_name => {
const anon_func = function() {};
Object.defineProperty(anon_func, "name", {value: func_name, writable: false});
return anon_func;
};
const test11 = method1("DEF_PROP"); // No whitespace
console.log("DEF_PROP?", test11.name); // "DEF_PROP"
console.log("DEF_PROP?", demoeval(test11.toString()).name); // ""
const test12 = method1("DEF PROP"); // Whitespace
console.log("DEF PROP?", test12.name); // "DEF PROP"
console.log("DEF PROP?", demoeval(test12.toString()).name); // ""
// Function expression evaluation
const method2 = func_name => demoeval(`function ${func_name}() {}`);
const test21 = method2("EVAL_EXPR"); // No whitespace
console.log("EVAL_EXPR?", test21.name); // "EVAL_EXPR"
console.log("EVAL_EXPR?", demoeval(test21.toString()).name); // "EVAL_EXPR"
const test22 = method2("EVAL EXPR"); // Uncaught SyntaxError: Unexpected identifier
If you want to have a dynamic function like the __call function in PHP, you could use Proxies.
const target = {};
const handler = {
get: function (target, name) {
return (myArg) => {
return new Promise(resolve => setTimeout(() => resolve('some' + myArg), 600))
}
}
};
const proxy = new Proxy(target, handler);
(async function() {
const result = await proxy.foo('string')
console.log('result', result) // 'result somestring' after 600 ms
})()
You can use Dynamic Function Name and parameters like this.
1) Define function Separate and call it
let functionName = "testFunction";
let param = {"param1":1 , "param2":2};
var func = new Function(
"return " + functionName
)();
func(param);
function testFunction(params){
alert(params.param1);
}
2) Define function code dynamic
let functionName = "testFunction(params)";
let param = {"param1":"1" , "param2":"2"};
let functionBody = "{ alert(params.param1)}";
var func = new Function(
"return function " + functionName + functionBody
)();
func(param);
This utility function merge multiple functions into one (using a custom name), only requirement is that provided functions are properly "new lined" at start and end of its scoop.
const createFn = function(name, functions, strict=false) {
var cr = `\n`, a = [ 'return function ' + name + '(p) {' ];
for(var i=0, j=functions.length; i<j; i++) {
var str = functions[i].toString();
var s = str.indexOf(cr) + 1;
a.push(str.substr(s, str.lastIndexOf(cr) - s));
}
if(strict == true) {
a.unshift('\"use strict\";' + cr)
}
return new Function(a.join(cr) + cr + '}')();
}
// test
var a = function(p) {
console.log("this is from a");
}
var b = function(p) {
console.log("this is from b");
}
var c = function(p) {
console.log("p == " + p);
}
var abc = createFn('aGreatName', [a,b,c])
console.log(abc) // output: function aGreatName()
abc(123)
// output
this is from a
this is from b
p == 123
I had better luck in combining Darren's answer and kyernetikos's answer.
const nameFunction = function (fn, name) {
return Object.defineProperty(fn, 'name', {value: name, configurable: true});
};
/* __________________________________________________________________________ */
let myFunc = function oldName () {};
console.log(myFunc.name); // oldName
myFunc = nameFunction(myFunc, 'newName');
console.log(myFunc.name); // newName
Note: configurable is set to true to match the standard ES2015 spec for Function.name1
This especially helped in getting around an error in Webpack similar to this one.
Update: I was thinking of publishing this as an npm package, but this package from sindresorhus does exactly the same thing.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
I struggled a lot with this issue. #Albin solution worked like a charm while developing, but it did not work when I changed it to production. After some debugging I realized how to achieve what I needed. I'm using ES6 with CRA (create-react-app), which means it's bundled by Webpack.
Lets say you have a file that exports the functions you need:
myFunctions.js
export function setItem(params) {
// ...
}
export function setUser(params) {
// ...
}
export function setPost(params) {
// ...
}
export function setReply(params) {
// ...
}
And you need to dynamically call these functions elsewhere:
myApiCalls.js
import * as myFunctions from 'path_to/myFunctions';
/* note that myFunctions is imported as an array,
* which means its elements can be easily accessed
* using an index. You can console.log(myFunctions).
*/
function accessMyFunctions(res) {
// lets say it receives an API response
if (res.status === 200 && res.data) {
const { data } = res;
// I want to read all properties in data object and
// call a function based on properties names.
for (const key in data) {
if (data.hasOwnProperty(key)) {
// you can skip some properties that are usually embedded in
// a normal response
if (key !== 'success' && key !== 'msg') {
// I'm using a function to capitalize the key, which is
// used to dynamically create the function's name I need.
// Note that it does not create the function, it's just a
// way to access the desired index on myFunctions array.
const name = `set${capitalizeFirstLetter(key)}`;
// surround it with try/catch, otherwise all unexpected properties in
// data object will break your code.
try {
// finally, use it.
myFunctions[name](data[key]);
} catch (error) {
console.log(name, 'does not exist');
console.log(error);
}
}
}
}
}
}
Node.js JavaScript Class Based Dynamic Function Name
File: Schema.js
class Schema {
constructor() {
this.name = null;
}
virtual(name = null) {
this.name = name;
return this;
}
get(func = false) {
if (!this.name || !func instanceof Function) {
throw new Error("Name and function must be provided.");
}
// Attach the dynamic function name to the "this" Object
this[this.name] = func;
this.name = null;
}
}
module.exports = Schema;
File: index.js
const Schema = require("./Schema.js");
const User = new Schema();
User.virtual("getPostCount").get(() => {
return 10 + 10;
});
const ok = User.getPostCount();
console.log({ User });
console.log(ok);
Thank you Marcosc! Building on his answer, if you want to rename any function, use this:
// returns the function named with the passed name
function namedFunction(name, fn) {
return new Function('fn',
"return function " + name + "(){ return fn.apply(this,arguments)}"
)(fn)
}
function myFunction() {
console.log('It works!');
}
var name = 'myFunction';
window[name].call();
You was near:
this["instance_" + a] = function () {...};
{...};
I might be missing the obvious here, but what's wrong with just adding the name? functions are invoked regardless of their name. names are just used for scoping reasons. if you assign it to a variable, and it's in scope, it can be called. hat happens is your are executing a variable which happens to be a function. if you must have a name for identification reasons when debugging, insert it between the keyword function and the opening brace.
var namedFunction = function namedFunction (a,b) {return a+b};
alert(namedFunction(1,2));
alert(namedFunction.name);
alert(namedFunction.toString());
an alternative approach is to wrap the function in an outer renamed shim, which you can also pass into an outer wrapper, if you don't want to dirty the surrounding namespace. if you are wanting to actually dynamically create the function from strings (which most of these examples do), it's trivial to rename the source to do what you want. if however you want to rename existing functions without affecting their functionality when called elsewhere, a shim is the only way to achieve it.
(function(renamedFunction) {
alert(renamedFunction(1,2));
alert(renamedFunction.name);
alert(renamedFunction.toString());
alert(renamedFunction.apply(this,[1,2]));
})(function renamedFunction(){return namedFunction.apply(this,arguments);});
function namedFunction(a,b){return a+b};
This is BEST solution, better then new Function('return function name(){}')().
Eval is fastest solution:
var name = 'FuncName'
var func = eval("(function " + name + "(){})")