3

In JavaScript, when I define function like this

function aaa(){}

I can later access the name by name attribute:

aaa.name

which will return

"aaa"

However, when I define function via var, it technically should be anonymous function without name attribute:

var aaa=function(){}

But instead it assumes that aaa is function name and assigns it to name attribute:

aaa.name

will also return

"aaa"

How JavaScript decides what should be the name, especially considering the fact that assignments could use more complicated scenarios:

var aaa=bbb=function(){} or var aaa=arr[0]=function(){}

?

1

2 Answers 2

1

Javascript declares the name variable of the function by taking the left-hand side argument that is equal to the function, which is 'aaa' in all basic cases. In the first complex definition, you declared state above Javascript will take the variable ab and assign it to a function making the name 'ab'. In the final example, you provided it sets the function equal to a pointer in memory, which is not a defined variable, this sets the name property to an empty string because arr[0] is not a variable name but a pointer to memory. Here is a JSFiddle displaying this.

Sign up to request clarification or add additional context in comments.

Comments

1

Something like this:

Inferred function names

Variables and methods can infer the name of an anonymous function from its syntactic position (new in ECMAScript 2015).

var f = function() {}; 
var object = {   
    someMethod: function() {} 
};
console.log(f.name); // "f" 
console.log(object.someMethod.name); // "someMethod"

Read the entire blog. It will clear all your queries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.