简体   繁体   中英

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
    }
}

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.

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 :-)

The best way to do it would be like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM