Technically - it doesn't matter.
var myFunction = function() { } //anonymous
and
var myFunction = function myFunction() { } //named
Will be identical in all regards but one - using debug tools and looking at stack traces will show different identifiers. The first version will show up as (anonymous function)
while the latter will show up with its name - myFunction
. So, named functions are purely for developer convenience and for development.
Worth noting that the name of the function does not need to be the same as the reference to it, for example you can have
var myFunction = function someOtherName() { /* ... */ }
and then this will show up as someOtherName
in dev tools. However you will not be able to call it by doing someOtherName()
- the name and the reference to the function are different things. For simplicity they are usually set to the same identifier.
Now, onto your example - there is a difference to what you posted
function myFunc() {
this.myMethod = () => {
//..
}
}
This is not equivalent to a named function. This is using the ES6 arrow functions - normally, they will be named the same as the variable they are assigned to:
var arrowFunction = () => {};
var obj = {
arrowMethod: () => {}
}
console.log("function name is: " + arrowFunction.name);
console.log("object property function name is: "+ obj.arrowMethod.name);
(note that this works in Chrome but not in Firefox for some reason - the .name
property is supposed to be set)
Further to the naming differences, arrow functions have other differences to a "plain" function. Most notably, their context is lexically bound. Here is what this means in practice
function arrowExample() {
this.data = "Hello arrow";
this.myMethod = () => {
return this.data;
}
}
function normalFunctionExample() {
this.data = "Hello normal function";
this.myMethod = function myMethod() {
return this.data;
}
}
var arrowInstance = new arrowExample();
var normalFunctionExampleInstance = new normalFunctionExample();
console.log("Invoking arrow with context: " + arrowInstance.myMethod());
console.log("Invoking normal function with context: " + normalFunctionExampleInstance.myMethod());
var arrowReference = arrowInstance.myMethod;
var normalFunctionReference = normalFunctionExampleInstance.myMethod;
console.log("Invoking arrow without context: " + arrowReference());
console.log("Invoking normal function without context: " + normalFunctionReference());