Reputation: 11
I was trying to define a function with constructor Function as below, but why the name of the function return anonymous?
let sayHi = new Function('alert("Hello")');
//this will return anonymous
sayHi.name
Upvotes: 0
Views: 66
Reputation: 1075249
...but why the name of the function return anonymous?
Because that's how the Function
constructor is defined. This is covered by the spec. The Function
constructor calls the abstract operation CreateDynamicFunction, which sets the name to "anonymous"
near the end:
- Perform SetFunctionName(F, "anonymous").
This is in contrast to a non-dynamic function with no name, which is relatively difficult to create these days because ES2015 defined that names are assigned to functions created with anonymous (!) function expressions in most situations.
The exception is assigning to a property on a pre-existing object:
const o = {};
o.foo = function() { };
console.log(o.foo.name); // ""
Just for completeness, here are some functions that use neither ""
nor "anonymous"
as their name
:
function foo() {
}
console.log(foo.name);
const bar = function() { };
console.log(bar.name);
const baz = () => { };
console.log(baz.name);
(Yes, those second two are assigned a name as specified behavior; see this answer for details.)
Upvotes: 2
Reputation: 3386
Functions created with the syntax new Function(...)
or just Function(...)
create Function objects and their name is "anonymous".
(new Function).name; // "anonymous"
Hope this helps you!
Upvotes: -1
Reputation: 6501
Function constructor does not accept a name, therefore it is always anonymous as specified in the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
Upvotes: 0
Reputation: 152284
This happens because you are creating anonymouse function.
Named functions are initialized with:
function sayHi() {
alert('Hello');
};
sayHi.name // sayHi
Upvotes: 6