A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

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

trusktr
2015-10-30

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() {}

and

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() {}
Edwin_Reynoso
2015-10-30

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

a = function b(){}
a.name; // "b"
a.name = "a";
a.name; // "a"
MT
2015-10-30

Why not just:

var someFunction = function() {};

?

trusktr
2015-11-09

That’s not a named function.

trusktr
2015-11-09

@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.

MT
2015-11-09
var someFunction = function() {};

and

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?

trusktr
2015-11-10

@MT

https://kangax.github.io/nfe/

and

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.

Edwin_Reynoso
2015-11-10

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