Search code examples
javascriptjavascript-objects

JavaScript naming object functions


Fairly new to JS,

Using a simple example of an object with a function:

var person = {
    name: "Bob McBobson",
    talk: function descriptiveFunctionName() {alert("Hello");}
};

I've noticed you can name object functions (e.g. descriptiveFunctionName above)

Are there any cases where this would be needed/helpful rather than leaving anonymous?


Solution

  • Are there any cases where this would be needed/helpful rather than leaving anonymous?

    As of ES2015, even if you left out descriptiveFunctionName there, your function wouldn't be anonymous, it would have a name (talk). ES2015 added inferred function names (and the name property, finally). Names are inferred in the majority of situations, with the only really important place they aren't inferred being obj.foo = function() { } (which leaves the function with the name "", not "foo").

    Separately, if the function will be recursive or otherwise refer to itself (set itself as an event handler, etc.), you may prefer to reference it by its name (which is in-scope within it).

    So, reasons for adding the name:

    1. If you're creating the object as shown in your question and you want the function's actual name not to match the property you're initializing with the function.
    2. If you're doing obj.foo = function nameHere() { }; and you want the function to have a name rather than "".
    3. It will refer to itself and you want to use that name rather than the object property.