uloco
uloco

Reputation: 2421

Property name same as non anonymous function

I'd like to use non anonymous functions for a better debugging purpose and encountered the following question.

When I have a function returning an object of methods (like in angularjs factories), is it bad style to name the returned property and the function the same?

Like here:

angular
    .module('myModule', [])
    .factory('foobar', foobar);

function foobar() {
    return {
        foo: function foo() {console.log('foo')},     //Is this ok
        bar: function barFunc() {console.log('bar')}  //Or this way better
    }
}

Upvotes: 0

Views: 40

Answers (3)

tomasz stryjewski
tomasz stryjewski

Reputation: 168

both options are totally fine - the only difference you will get is that while debugging you'll see function's name instead of anonymous function which is REALLY useful.

so to sum it up - I would advise you to name them, but the naming is totally up to you :-)

Upvotes: 1

Bergi
Bergi

Reputation: 664165

This is not a question of style, and doesn't have a definitive answer. There is surely nothing wrong with naming the function expression the same as the property.

However, you are aiming for a better debugging experience. So you should ask yourself: "What name helps me best to identify the function in my code by its name?". Whether that might be foo, fooFunc, foobar_foo (including the module name) or anything else, you will have to decide yourself.

Upvotes: 2

Tom Arad
Tom Arad

Reputation: 251

The best way to do it would be like so:

function foobar() {
  return {
    foo() { console.log('foo') }
  };
}

Upvotes: 0

Related Questions