简体   繁体   English

属性名称与非匿名函数相同

[英]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? 当我有一个函数返回方法的对象时(例如在angularjs工厂中),将返回的属性和函数命名为相同的样式是否不好?

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. 无论是foofooFuncfoobar_foo (包括模块名称)还是其他任何东西,您都必须自己决定。

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. 这两个选项都很好-您将获得的唯一区别是,在调试时,您将看到函数的名称,而不是真正有用的anonymous function

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') }
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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