简体   繁体   中英

the name of function return anonymous when I define a function with new Function

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

This happens because you are creating anonymouse function.

Named functions are initialized with:

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

sayHi.name // sayHi

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

函数构造函数不接受名称,因此,它始终是docs中指定的匿名名称: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/name

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM