Javascript: functions in an object automatically get a name (or not) depending on the syntax of the declaration - why?

I have no problems, I'm not trying to fix anything. I'm just wondering why Javascript works this way. I poked using google, but "js function no name" gets a lot of views on how to define and use anonymous functions (not what I'm looking for). And almost nothing is said there about declaring functions with syntax causing my confusion - I don’t even know what this syntax is called.

Problem . I am trying to understand why the declaration syntax affects the function name when the function is inside the object. If I declare an object with a function inside as follows:

var objectOne = { apple: function() {} } 

The apple() function gets the name. That is, console.log(objectOne.apple.name) displays "apple".

But if I declare an object with a function inside:

 var objectTwo = {} objectTwo.banana = function() {} 

Then banana() does not get the name. That is, console.log(objectTwo.banana.name) does not display anything. The same goes for the following and similar permutations.

 var objectThree = { catapult: null } objectThree.catapult = function() {} 

I can name the functions explicitly, but, again, I'm not trying to fix anything, just wondering why the two syntaxes give different results. I have always considered them functionally interchangeable.

I noticed that both of these forms, and not inside the object, automatically get the names:

  function one() {} var two = function() {} 

Why is the form object.property = function(){} handled differently than other forms?

+7
javascript function object
source share
1 answer

From the ECMA specification on how the function name is set:

SetFunctionName (F, name, prefix)

The abstract operation SetFunctionName requires an argument to the F function, a string or a character argument name, and an optional prefix to the String argument. This operation adds the name property to F by following these steps:

Assert: F is an extensible object that does not have its own name property.

Statement: A type (name) is either a character or a string.

Assert: If the prefix was passed, then Type (prefix) is String.

If type (name) is a symbol, then

Let the description be the name [[Description]].

If the description is undefined, let the name be an empty String.

Otherwise, let the name be a concatenation of "[", description and "]".

If the prefix has been transmitted, then

Let the name be the concatenation of the prefix, code 0x0020 (SPACE) and the name.

Return DefinePropertyOrThrow (F, "name", PropertyDescriptor {[[Value]]: name, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true}).

Statement: the result is never a sharp end.

My assumption is that the second example did not pass the first test to set the function name (Assert: F is an extensible object), and therefore the name will not be set.

0
source share

All Articles