0

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
NoDev
  • 11
  • 2

4 Answers4

6

This happens because you are creating anonymouse function.

Named functions are initialized with:

function sayHi() {
  alert('Hello');
};

sayHi.name // sayHi
hsz
  • 148,279
  • 62
  • 259
  • 315
  • This doesn't explain the name `"anonymous"`, particularly since other anonymous functions have a blank name. The real answer here is: Because that's how the `Function` constructor is defined (as of ES2015). – T.J. Crowder Jul 19 '18 at 08:27
2

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

  1. 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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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

ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22
-1

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!

Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20