简体   繁体   English

Airbnb的ES6风格指南功能推荐

[英]Airbnb's ES6 style guide recommendation about functions

Referring to section 7.1 in the style guide: 请参阅样式指南中的7.1节:

// bad
function foo() {
}

// good
const foo = function bar() {
};

I can't seem to understand what exactly is wrong with the first statement ? 我似乎无法理解第一句话到底出了什么问题? How is it bad ? 有多糟糕? (fyi .. I do understand the difference that the first declaration is hoisted and the 'const' do not get hoisted. What I do not understand is being hoisted bad ? (fyi ..我确实理解了第一个声明被吊起和'const'不被吊起的区别。我不理解被吊起的不好吗?

AirBnB has already explained why they consider function declarations hosting a bad thing here : AirBnB已经解释了为什么他们认为在这里托管功能不好的函数声明:

7.1 Use named function expressions instead of function declarations. 7.1使用命名函数表达式而不是函数声明。

Why? 为什么? Function declarations are hoisted, which means that it's easy - too easy - to reference the function before it is defined in the file. 悬挂了函数声明,这意味着在文件中定义函数之前就很容易(太容易了)引用函数。 This harms readability and maintainability. 这会损害可读性和可维护性。 If you find that a function's definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it's time to extract it to its own module! 如果发现函数的定义足够大或过于复杂,以至于妨碍了对文件其余部分的理解,那么也许是时候将其提取到自己的模块中了! Don't forget to name the expression - anonymous functions can make it harder to locate the problem in an Error's call stack. 别忘了给表达式命名-匿名函数会使在Error的调用堆栈中定位问题变得更加困难。

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

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