Is it possible to set the name of a function at runtime in JavaScript?
var ctor = function() {}; // Anonymous function because I don't know the name ahead of runtime.
ctor.name = 'foo'; // Pseudocode - this is effectively what I want to do
I want the above to be equivalent to:
var ctor = function foo() {};
Edit
Here is an example use-case:
function mix(fn1, fn2, name) {
var ctor = function() {};
ctor.name = name; // Vain attempt to set the name of the function.
ctor.prototype = Object.create(fn1.prototype);
Object.keys(fn2.prototype).map(function(k) {
ctor.prototype[k] = fn2.prototype[k];
});
// Return a constructor function with the prototype configured.
return ctor;
}
function Foo() {}
Foo.prototype.foo = function(){};
function Bar(){}
Bar.prototype.bar = function() {};
var Foobar = mix(Foo, Bar, 'Foobar');
console.log(new Foobar()); // ctor {bar: function, foo: function} (in Chrome) - I wanted Foobar { bar: function, foo: function }
name was a non-standard only supported by some browsers.
Now, it has been standardized in ECMAScript 6:
19.2.4.2 name
The value of the
nameproperty is an String that is descriptive of the function. The name has no semantic significance but is typically a variable or property name that is used to refer to the function at its point of definition in ECMAScript code. This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.Anonymous functions objects that do not have a contextual name associated with them by this specification do not have a
nameown property but inherit thenameproperty of %FunctionPrototype%.
Therefore, your code will work on browsers that don't support name, but the new property will be writable and enumerable. And on browsers that support it, your code won't work because name is not writable.
Therefore, a better equivalent code would be
Object.defineProperty(ctor, 'name', {
value: 'foo',
configurable: true
});
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