javascript改样式_Google JavaScript样式指南的13点值得注意

javascript改样式

by Daniel Simmons

丹尼尔·西蒙斯(Daniel Simmons)

Google JavaScript样式指南的13点值得注意 (13 Noteworthy Points from Google’s JavaScript Style Guide)

For anyone who isn’t already familiar with it, Google puts out a style guide for writing JavaScript that lays out (what Google believes to be) the best stylistic practices for writing clean, understandable code.

对于尚未熟悉它的任何人, Google都会提供一个用于编写JavaScript 的样式指南 ,该指南提供了(编写Google认为的)编写清晰易懂的代码的最佳样式实践。

These are not hard and fast rules for writing valid JavaScript, only proscriptions for maintaining consistent and appealing style choices throughout your source files. This is particularly interesting for JavaScript, which is a flexible and forgiving language that allows for a wide variety of stylistic choices.

这些不是编写有效JavaScript的硬性规定,只是用于在整个源文件中保持一致且有吸引力的样式选择的规定。 对于JavaScript而言,这尤其有趣,它是一种灵活且宽容的语言,可以进行多种样式选择。

Google and Airbnb have two of the most popular style guides out there. I’d definitely recommend you check out both of them if you spend much time writing JS.

Google和Airbnb提供了两个最受欢迎的样式指南。 如果您花费大量时间编写JS,我绝对建议您将它们都检查一下。

The following are thirteen of what I think are the most interesting and relevant rules from Google’s JS Style Guide.

以下是我认为是Google JS样式指南中最有趣和最相关的规则中的十三条。

They deal with everything from hotly contested issues (tabs versus spaces, and the controversial issue of how semicolons should be used), to a few more obscure specifications which surprised me. They will definitely change the way I write my JS going forward.

他们处理的问题从热烈争论的问题(制表符和空格,以及如何使用分号引起争议的问题),到一些晦涩难懂的规范,这些使我感到惊讶。 他们肯定会改变我以后编写JS的方式。

For each rule, I’ll give a summary of the specification, followed by a supporting quote from the style guide that describes the rule in detail. Where applicable, I’ll also provide an example of the style in practice, and contrast it with code that does not follow the rule.

对于每条规则,我将给出一个规范摘要,然后是样式指南中的支持报价,其中详细描述了该规则。 在适用的情况下,我还将提供实践中的样式示例,并将其与不遵循规则的代码进行对比。

使用空格,而不是制表符 (Use spaces, not tabs)

Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that… Tab characters are not used for indentation.

除了行终止符序列之外,ASCII水平空格字符(0x20)是唯一出现在源文件中任何地方的空格字符。 这意味着…制表符用于缩进。

The guide later specifies you should use two spaces (not four) for indentation.

指南稍后会指定缩进应使用两个空格(而不是四个)。

// badfunction foo() {∙∙∙∙let name;}// badfunction bar() {∙let name;}// goodfunction baz() {∙∙let name;}
需要分号 (Semicolons ARE required)
Every statement must be terminated with a semicolon. Relying on automatic semicolon insertion is forbidden.
每个语句必须以分号结尾。 禁止依靠自动分号插入。

Although I can’t imagine why anyone is opposed to this idea, the consistent use of semicolons in JS is becoming the new ‘spaces versus tabs’ debate. Google’s coming out firmly here in the defence of the semicolon.

尽管我无法想象为什么有人反对这个想法,但是在JS中对分号的一致使用正成为新的“空格与制表符”辩论。 Google在捍卫分号方面坚定地走在这里。

// badlet luke = {}let leia = {}[luke, leia].forEach(jedi => jedi.father = 'vader')
// goodlet luke = {};let leia = {};[luke, leia].forEach((jedi) => {  jedi.father = 'vader';});
暂不使用ES6模块 (Don’t use ES6 modules (yet))

Do not use ES6 modules yet (i.e. the export and import keywords), as their semantics are not yet finalized. Note that this policy will be revisited once the semantics are fully-standard.

尚未使用ES6模块(即exportimport关键字),因为它们的语义尚未最终确定。 请注意,一旦语义完全标准,该政策将被重新考虑。

// Don't do this kind of thing yet:
//------ lib.js ------export function square(x) {    return x * x;}export function diag(x, y) {    return sqrt(square(x) + square(y));}//------ main.js ------import { square, diag } from 'lib';
不建议水平对齐(但不禁止) (Horizontal alignment is discouraged (but not forbidden))

This practice is permitted, but it is generally discouraged by Google Style. It is not even required to maintain horizontal alignment in places where it was already used.

允许这种做法,但Google风格通常不鼓励这样做。 甚至不需要在已经使用过的地方保持水平对齐。

Horizontal alignment is the practice of adding a variable number of additional spaces in your code, to make certain tokens appear directly below certain other tokens on previous lines.

水平对齐是一种在代码中添加可变数量的额外空格的做法,以使某些标记直接出现在前几行中某些其他标记的下方。

// bad{  tiny:   42,    longer: 435, };
// good{  tiny: 42,   longer: 435,};
不再使用var (Don’t use var anymore)

Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used.

使用constlet声明所有局部变量。 默认情况下使用const,除非需要重新分配变量。 不得使用var关键字。

I still see people using var in code samples on StackOverflow and elsewhere. I can’t tell if there are people out there who will make a case for it, or if it’s just a case of old habits dying hard.

我仍然看到人们在StackOverflow和其他地方的代码示例中使用var 。 我不能说是否有人会为此辩护,或者仅仅是因为旧的习惯很难解决。

// badvar example = 42;
// goodlet example = 42;
首选箭头功能 (Arrow functions are preferred)

Arrow functions provide a concise syntax and fix a number of difficulties with this. Prefer arrow functions over the function keyword, particularly for nested functions

箭头的功能提供了一个简洁的语法和修复了一些困难this 。 优先使用箭头函数而不是function关键字,特别是对于嵌套函数

I’ll be honest, I just thought that arrow functions were great because they were more concise and nicer to look at. Turns out they also serve a pretty important purpose.

老实说,我只是认为箭头功能很棒,因为它们更简洁,更美观。 事实证明,它们也起到了非常重要的作用。

// bad[1, 2, 3].map(function (x) {  const y = x + 1;  return x * y;});// good[1, 2, 3].map((x) => {  const y = x + 1;  return x * y;});
使用模板字符串而不是串联 (Use template strings instead of concatenation)

Use template strings (delimited with `) over complex string concatenation, particularly if multiple string literals are involved. Template strings may span multiple lines.

在复杂的字符串连接上使用模板字符串(以`分隔),尤其是在涉及多个字符串文字的情况下。 模板字符串可能跨越多行。

// badfunction sayHi(name) {  return 'How are you, ' + name + '?';}// badfunction sayHi(name) {  return ['How are you, ', name, '?'].join();}// badfunction sayHi(name) {  return `How are you, ${ name }?`;}// goodfunction sayHi(name) {  return `How are you, ${name}?`;}
不要对长字符串使用换行符 (Don’t use line continuations for long strings)

Do not use line continuations (that is, ending a line inside a string literal with a backslash) in either ordinary or template string literals. Even though ES5 allows this, it can lead to tricky errors if any trailing whitespace comes after the slash, and is less obvious to readers.

在普通或模板字符串文字中,请勿使用行继续 (即,在字符串文字中的行以反斜杠结束)。 即使ES5允许这样做,但如果在斜杠后出现任何尾随空格,则可能导致棘手的错误,并且对读者而言不太明显。

Interestingly enough, this is a rule that Google and Airbnb disagree on (here’s Airbnb’s spec).

有趣的是,这是Google和Airbnb意见不一致的一条规则(这是Airbnb的规格 )。

While Google recommends concatenating longer strings (as shown below) Airbnb’s style guide recommends essentially doing nothing, and allowing long strings to go on as long as they need to.

虽然Google建议连接较长的字符串(如下所示),但Airbnb的样式指南建议实质上不做任何事情,并允许长字符串在需要时继续使用。

// bad (sorry, this doesn't show up well on mobile)const longString = 'This is a very long string that \    far exceeds the 80 column limit. It unfortunately \    contains long stretches of spaces due to how the \    continued lines are indented.';
// goodconst longString = 'This is a very long string that ' +     'far exceeds the 80 column limit. It does not contain ' +     'long stretches of spaces since the concatenated ' +    'strings are cleaner.';
“ for…of”是“ for循环”的首选类型 (“for… of” is the preferred type of ‘for loop’)

With ES6, the language now has three different kinds of for loops. All may be used, though for-of loops should be preferred when possible.

使用ES6,该语言现在具有三种不同的for循环。 所有可以使用,但for - of循环应该是首选在可能的情况。

This is a strange one if you ask me, but I thought I’d include it because it is pretty interesting that Google declares a preferred type of for loop.

如果您问我,这很奇怪,但是我认为我应该包括它,因为Google声明一种首选的for循环类型非常有趣。

I was always under the impression that for... in loops were better for objects, while for... of were better suited to arrays. A ‘right tool for the right job’ type situation.

我总是对for... in循环中的对象更好,而for... of数组更适合。 一种“正确的工具,适合正确的工作”类型的情况。

While Google’s specification here doesn’t necessarily contradict that idea, it is still interesting to know they have a preference for this loop in particular.

尽管Google的规范不一定与该思想相抵触,但有趣的是,他们特别喜欢此循环。

不要使用eval() (Don’t use eval())

Do not use eval or the Function(...string) constructor (except for code loaders). These features are potentially dangerous and simply do not work in CSP environments.

不要使用evalFunction(...string)构造函数(代码加载器除外)。 这些功能具有潜在的危险,根本无法在CSP环境中使用。

The MDN page for eval() even has a section called “Don’t use eval!”

eval()MDN页面甚至有一个名为“请勿使用eval!”的部分。

// badlet obj = { a: 20, b: 30 };let propName = getPropName();  // returns "a" or "b"eval( 'var result = obj.' + propName );
// goodlet obj = { a: 20, b: 30 };let propName = getPropName();  // returns "a" or "b"let result = obj[ propName ];  //  obj[ "a" ] is the same as obj.a
常量应以ALL_UPPERCASE命名,并用下划线分隔 (Constants should be named in ALL_UPPERCASE separated by underscores)

Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores.

常量名称使用CONSTANT_CASE :所有大写字母,单词之间用下划线分隔。

If you’re absolutely sure that a variable shouldn’t change, you can indicate this by capitalizing the name of the constant. This makes the constant’s immutability obvious as it gets used throughout your code.

如果您绝对确定不应该更改变量,则可以通过大写常量名称来表明这一点。 这使得常量的不变性在整个代码中都得到使用。

A notable exception to this rule is if the constant is function-scoped. In this case it should be written in camelCase.

该规则的一个明显例外是常量是否是函数范围的。 在这种情况下,应使用camelCase编写。

// badconst number = 5;
// goodconst NUMBER = 5;
每个声明一个变量 (One variable per declaration)

Every local variable declaration declares only one variable: declarations such as let a = 1, b = 2; are not used.

每个局部变量声明仅声明一个变量:例如let a = 1, b = 2; 不使用。

// badlet a = 1, b = 2, c = 3;
// goodlet a = 1;let b = 2;let c = 3;
使用单引号,而不是双引号 (Use single quotes, not double quotes)

Ordinary string literals are delimited with single quotes ('), rather than double quotes (").

普通字符串文字用单引号( ' )而不是双引号( " )分隔。

Tip: if a string contains a single quote character, consider using a template string to avoid having to escape the quote.
提示:如果字符串包含单引号字符,请考虑使用模板字符串,以避免不得不对引号进行转义。
// badlet directive = "No identification of self or mission."
// badlet saying = 'Say it ain\u0027t so.';
// goodlet directive = 'No identification of self or mission.';
// goodlet saying = `Say it ain't so`;
最后的笔记 (A final note)

As I said in the beginning, these are not mandates. Google is just one of many tech giants, and these are just recommendations.

正如我在开始时所说,这些不是强制性的。 Google只是众多科技巨头之一,而这些只是推荐。

That said, it is interesting to look at the style recommendations that are put out by a company like Google, which employs a lot of brilliant people who spend a lot of time writing excellent code.

也就是说,看看像Google这样的公司提出的样式建议很有趣,该公司雇用了许多才华横溢的人,他们花费大量时间编写出色的代码。

You can follow these rules if you want to follow the guidelines for ‘Google compliant source code’ — but, of course, plenty of people disagree, and you’re free to brush any or all of this off.

如果您想遵循“符合Google要求的源代码”的准则,则可以遵循这些规则-但是,当然,很多人对此表示反对,您可以随意取消其中的任何一项或全部。

I personally think there are plenty of cases where Airbnb’s spec is more appealing than Google’s. No matter the stance you take on these particular rules, it is still important to keep stylistic consistency in mind when write any sort of code.

我个人认为,在很多情况下,Airbnb的规范比Google更具吸引力。 无论您对这些特定规则采取何种立场,编写任何类型的代码时都要牢记样式的一致性仍然很重要。

翻译自: https://www.freecodecamp.org/news/google-publishes-a-javascript-style-guide-here-are-some-key-lessons-1810b8ad050b/

javascript改样式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值