Javascript 简明教程

JavaScript - Style Guide

JavaScript 风格指南是一组通用规则,规定了如何编写 JavaScript 代码。这些规则可以包括 − 使用哪些引号、缩进多少个空格、最长行长度、使用单行注释(标记为 //)等。

A JavaScript style guide is a set of general rules that regulate how to write JavaScript code. These rules can include − which quotes to use, how many spaces to indent, the maximum line length, using single-line comments, marked with //, etc.

当任何公司开始开发实时 JavaScript 项目时,数百名开发人员会参与其中。如果每个开发人员遵循不同的编码风格,则管理复杂代码将变得非常困难。因此,在整个项目中遵循相同的代码风格非常重要。

When any company starts developing a real-time JavaScript project, 100’s of developers work on that. If each developer follows a different style of writing code, it becomes very hard to manage complex code. So, it is important to follow the same code style throughout the project.

在这里,我们介绍了一些在开发项目时应遵循的基本编码约定。

Here, we have covered some essential coding conventions to follow while developing the project.

Code Indentation

根据项目的编码约定,您应该始终使用固定空格缩进您的代码(2、3 或 4 个空格)。此外,代码不应包含尾随空格。

You should always intend your code with fixed spaces (either 2, 3 or 4 spaces) according to the coding convention of your project. Also, the code should not contain trailing white spaces.

Example

在下面的代码中,我们在函数中使用了三个空格缩进。

In the code below, we have used the three spaces indentation in the function.

<html>
   <body>
      <h2> Intendation Conventions </h2>
      <div id = "output"> </div>
      <script>
         const output = document.getElementById('output');
         function func() {
            output.innerHTML = "Function executed!";
            return 10;
         }
         func();
      </script>
   </body>
</html>

Comments

您应该始终使用行注释而不是块注释,并且行注释应该从代码的左侧开始。

You should always use the line comments rather than the block comments, and line comments should start with the left part of the code.

Example

在下面的代码中,我们使用“//”行注释对代码进行注释。

In the code below, we used the ‘//’ line comments to comment the code.

<html>
<body>
   <h2> Comment Conventions </h2>
   <div id="output"> </div>
   <script>
      const output = document.getElementById('output');
      output.innerHTML = "Hello World!";
      // var a = 10;
      // var b = 20;
   </script>
</body>
</html>

Variable Declaration

始终在变量作用域的顶部声明变量。如果变量是全局变量,请将其声明在文件顶部。同样,如果变量位于块或函数中,请将其声明在块或函数的顶部。此外,变量名称必须以字母开头。

Always declare the variable at the top of its scope. If a variable is a global variable, declare it at the top of the file. Similarly, if the variable is in th block or function, declare it at the top of the block or function. Furthermore, variable names must start with the letter.

Example

在下面的代码中,我们在代码顶部声明了变量,并且每个变量的名称都以字母开头。

In the code below, we have declared the variable at the top of the code, and the name of each variable starts with a letter.

<html>
<body>
   <h2> Variable Conventions </h2>
   <div id="output"> </div>
   <script>
      var a = 10;
      var b = 20;
      document.getElementById('output').innerHTML =
		"The sum of 10 and 20 is: " + (a + b);
   </script>
</body>
</html>

Identifier Names in camelCase

在 JavaScript 中,始终使用驼峰命名法来定义标识符。在驼峰命名法中,标识符的第一个字母应为小写,第二个单词的第一个字母应为大写。此处,标识符包括函数名、变量名、对象名、类名等。

In JavaScript, always use the camelCase convention to define the identifier. In the camelCase convention, the first letter of the identifier should be lowercase, and the first letter of the 2nd word should be in the uppercase. Here, identifiers include function names, variable names, object names, class names, etc.

Example

在下面的代码中,“greetMessage”和“executeGreet”这两个标识符都采用驼峰命名法。

In the code below, 'greetMessage' and 'executeGreet' both identifiers are in the camelCase.

<html>
<body>
   <h2> camelCase Conventions </h2>
   <div id="output"> </div>
   <script>
      var greetMessage = "Hello Developers!";
      let output = document.getElementById('output');
      // Function name with camelCase
      function executeGreet() {
         output.innerHTML = greetMessage;
      }
      executeGreet();
   </script>
</body>
</html>

Spaces, and Brackets

在 JavaScript 中,我们应该在“+”、“typeof”等每个运算符前后包括空格。此外,在括号周围包含空格也很重要。

In JavaScript, we should include white space before and after each operator like ‘+’, 'typeof’, etc. Furthermore, it is also vital to include white space around brackets.

Example

在下面的代码中,我们在“if”条件之后添加了适当的空格。此外,我们在“+=”运算符前后添加了空格。

In the code below, we added proper space after the 'if' condition. Also, we added white space before and after ‘+=’ operator.

<html>
<body>
   <h2> Space and all brackets Conventions </h2>
   <div id="output"> </div>
   <script>
      let output = document.getElementById('output');
      if (9 > 10) {
         output.innerHTML += "9 is greater than 10";
      } else {
         output.innerHTML += "9 is not greater than 10";
      }
   </script>
</body>
</html>

Object Rules

在 JavaScript 中,我们使用“=”赋值运算符并在对象标识符后打开大括号“{”。接下来,我们编写对象属性(用分号分隔的关键值对),并将每个属性写在新行中并用逗号 (,) 分隔它们。此外,我们不会在最后一个对象属性后放置逗号。最后,在添加关闭括号后添加分号 (;)。

In JavaScript, we use the ‘=’ assignment operator and open bracket ‘{‘ after the object identifier. Next, we write the object properties (key-value pairs separated by semicolon), and we write each property in the new line and separate them with a comma (,). Also, we don’t put a comma after the last object property. At the end, we add a semicolon (;) after adding a closing bracket.

Example

在下面的代码中,我们根据对象指南定义了对象。此外,我们使用 JSON.stringify() 方法在网页上显示对象。

In the code below, we have defined the object according to the object guidelines. Also, we have shown objects on the web page using the JSON.stringify() method.

<html>
<body>
   <h2> Object Conventions </h2>
   <div id="output"> </div>
   <script>
      const obj = {
         prop1: 'value1',
         prop2: 'value2',
         prop3: 'value3'
      };
      document.getElementById("output").innerHTML = JSON.stringify(obj, null, 2);
</script>
</body>
</html>

Statement Rules

JavaScript 中有 3 种类型的语句。

There are 3 types of statements in JavaScript.

  1. Simple one-line statement

  2. Compound statement

  3. Multi-line statement

简单的单行语句应始终以分号结尾。

The simple one-line statement should always end with a semicolon.

对于复合语句,我们在同一行中的语句后放置空格和一个打开的括号。接下来,我们开始从下一行添加语句体,并在最后一行添加一个关闭括号。我们在关闭括号后不加分号。

For the compound statement, we put white space and an open bracket after a statement in the same line. Next, we start adding the statement body from the next line, and in the last line, we add a closing bracket. We don’t put a semicolon after the closing bracket.

如果语句过长,无法写在一行中,我们可以在运算符后加一个换行符。

If the statement is too long and can’t be written in a single line, we can add a line break after the operator.

Example

在下面的代码中,我们定义了单一行、复合和多行的语句。

In the code below, we have defined single one-line, compound, and multi-line statements.

<html>
<body>
<h2> Statement Guidelines Conventions </h2>
<div id="output"> </div>
<script>
   const output = document.getElementById('output');
   // single line statement
   const arr = ["one", "two", "Three"];

   // Compound statement
   for (let i = 0; i < arr.length; i++) {
      output.innerHTML += arr[i] + "<br>";
   }

   // Multi-line statement
   if (10 > 9 && 10 > 5 && 10 > 6) {
      output.innerHTML += "10 is greater than 9 and 10 is greater than 5 <br>";
   }
</script>
</body>
</html>

Line Length

总是难以阅读长代码行。因此,我们应该将每行限制在 80 个字符内。

It is always hard to read long lines of code. So, we should put a maximum 80 characters in a single line.

Example

在下面的代码中,我们将一个包含超过 80 个字符的字符串添加到了新行中。

In the code below, we have added half a string in a new line as it contains more than 80 characters.

<html>
<body>
   <h2> Line length Conventions </h2>
   <div id="output"> </div>
   <script>
      let str = `This is too long a sentence.
            Let's put the limit of 80 characters.`
      document.getElementById('output').innerHTML = str;
   </script>
</body>
</html>

我们在本教程中解释了常见的风格规范。但是,您可以拥有自己的编码规范并在整个项目中遵循它们。

We have explained the common style conventions in this tutorial. However, you can have your own coding conventions and follow them throughout the project.