Proposal: Let the Function constructor accept a name for creating named functions


It’d be nice to be able to programmatically create named functions. Two less-than-ideal solutions exist:

var name = "someFunction"
eval("var namedFunction = function " + name + "() {}")
console.log(namedFunction) // function someFunction() {}


var name = "someFunction"
var namedFunction = new Function("return function " + name + "() {}")()
console.log(namedFunction) // function someFunction() {}

But it’d be nice if we could do something like the following which would be almost equivalent to the previous examples:

var name = "someFunction"
var namedFunction = new Function("", name)
console.log(namedFunction) // function someFunction() {}


I’d just like to make the name property configurable/writable

a = function b(){}; // "b" = "a";; // "a"


Why not just:

var someFunction = function() {};



That’s not a named function.


@Edwin_Reynoso Another idea, maybe a syntax addition similar to dynamic properties in ES6, so:

var name = "someFunction"
var a = function [someFunction](){}

I don’t think the name should be configurable after the function has already been created. That might cause some confusion if the name of a function changes unexpectedly.

var someFunction = function() {};


function someFunction() {}

are basically equivalent (both can be called as someFunction()) except for that the first one works consistently when nested in other functions.

So what exactly the “named function” term means for you?




The reason they can be handy is for when trying to (for example) make named constructors in a class library (for example, my simple one called lowclass. In ES6 classes, class constructors are always named functions, and their name is that of the class.

Briefly, lowclass aims to allow a developer to strategically use different types of classes (they have different performance implications), not just ES6 classes. In lowclass, which currently only produces ES5 constructor-pattern-style classes, emulates ES6 named constructors. It’d be nice to have an actual API to make that happen with, and then assigns the constructor to Class.prototype.constructor of the created class, which is another behavior of ES6 classes.

I think that dynamic naming of functions similar to ES6 property initializers would be great, like in my previous example.


Yea I like that, there is some code I have where I actually want to do that