javascript: programming style

Original sentence: Https://Wangdoc.Com/javascript/index.Html

Programming Style

Outline

"Programming style" (programming style) refers to the style rules to write code. Different programmers, often have different programming styles.

It is said that the compiler specification called "rules of grammar" (grammar), which is the programmer must comply; and the compiler to ignore parts, called "programming style" (programming style), which is free to choose the programmer . This statement is not entirely correct, of course, programmers are free to choose the programming style, but good programming style helps to write higher quality, fewer errors, easier to maintain the program.

Therefore, the choice of programming style should not be based on personal preference, familiarity, typing and other factors, and to consider how best to make the code legible and reduce errors. Your choice, not your favorite style, but rather a way to articulate your intentions style. This is especially important for the JavaScript syntax for such a high degree of freedom of language.

Must keep in mind is that if you select a "programming style", they should insist on compliance with a variety of styles should not be mixed. If you join someone else's project, it should comply with existing style.

indentation

The first row of spaces and the Tab key, you can generate code indentation effect (indent).

Tab to save keystrokes, but different text editors are not the same for Tab's display, some display four spaces, and some show two spaces, so some people think, spacebar makes the display more uniform.

Whichever method you choose, it is acceptable to do is always stick to this option. Do not use the Tab key for a while, one will use the spacebar.

Blocks

If the code is determined and only the circulation line, JavaScript allows the block (block) braces are omitted.

if (a)
  b();
  c();

The above intent of this code may be the following.

if (a) {
  b();
  c();
}

However, the actual effect is so below.

if (a) {
  b();
}
  c();

Therefore, it is recommended to always use curly brackets denote blocks.

In addition, the position of the block chapeau braces, there are many different ways of writing. The most popular are two, one is first of all a brace on a separate line.

block
{
  // ...
}

Another is the First braces behind keyword.

block {
  // ...
}

Generally speaking, two different spelling are acceptable. However, the use of JavaScript to the latter, because JavaScript will automatically add a semicolon at the end of the sentence, causing some subtle error.

return
{
  key: value
};

// 相当于
return;
{
  key: value
};

The original intent of the code above is to return an object, but actually return undefinedbecause JavaScript automatically returnbehind the statement added semicolon. In order to avoid this type of error and needs to be written as follows.

return {
  key : value
};

So, first of all it represents a block of braces, do not start a new line.

Parentheses

Parentheses (parentheses) There are two functions in JavaScript, a representation of the function call, and the other represents a combination of expressions (grouping).

// 圆括号表示函数的调用
console.log('abc');

// 圆括号表示表达式的组合
(1 + 2) * 3

Recommended by spaces we can distinguish between these two different brackets.

  1. Represents a function call, there is no space between the function name and the opening parenthesis.

  2. When expressed as a function definition, there is no space between the function name and the opening parenthesis.

  3. When other cases, the syntax elements between the front position and left bracket, there is a space.

According to the above rules, the following versions are not standardized.

foo (bar)
return(a+b);
if(a === 0) {...}
function foo (b) {...}
function(x) {...}

The last line of the code above is an anonymous function functionsyntax keyword, not a function name, so between the left parenthesis and should have a space.

Trailing semicolon

Semicolon indicates the end of a statement. JavaScript allows semicolon end of the line will be omitted. In fact, there are indeed some developers end of the line never write a semicolon. However, for reasons discussed below, it is recommended not to omit the semicolon.

Without the use of a semicolon

First, the following three cases, the provisions of grammar normally does not require a semicolon at the end.

(1) for loop and while

for ( ; ; ) {
} // 没有分号

while (true) {
} // 没有分号

Note that do...whilecycling is a semicolon.

do {
  a--;
} while(a > 0); // 分号不能省略

(2) branching statements: if, switch, try

if (true) {
} // 没有分号

switch () {
} // 没有分号

try {
} catch {
} // 没有分号

(3) function declaration

function f() {
} // 没有分号

Note that the function expression still want to use a semicolon.

var f = function f() {
};

The above three cases, if you use a semicolon, and not go wrong. Because the engine will interpret the semicolons interpreted as an empty statement.

Semicolon is automatically added

In addition to the one of the three cases, all the statements should use a semicolon. However, if you do not use semicolons, in most cases, JavaScript is automatically added.

var a = 1
// 等同于
var a = 1;

This syntax feature is called "semicolon is automatically added" (Automatic Semicolon Insertion, referred to as ASI).

Therefore, some people advocate the end of the sentence omitted semicolon. The trouble is, if the start of the next line can be tied together with the end of the line explained, JavaScript does not automatically add a semicolon.

// 等同于 var a = 3
var
a
=
3

// 等同于 'abc'.length
'abc'
.length

// 等同于 return a + b;
return a +
b;

// 等同于 obj.foo(arg1, arg2);
obj.foo(arg1,
arg2);

// 等同于 3 * 2 + 10 * (27 / 6)
3 * 2
+
10 * (27 / 6)

The code above will be explained together on multiple lines, each line will not automatically add a semicolon. These examples are quite easy to see, but the following example is not so easy to see out.

x = y
(function () {
  // ...
})();

// 等同于
x = y(function () {...})();

Here are some more examples does not automatically add a semicolon.

// 引擎解释为 c(d+e)
var a = b + c
(d+e).toString();

// 引擎解释为 a = b/hi/g.exec(c).map(d)
// 正则表达式的斜杠,会当作除法运算符
a = b
/hi/g.exec(c).map(d);

// 解释为'b'['red', 'green'],
// 即把字符串当作一个数组,按索引取值
var a = 'b'
['red', 'green'].forEach(function (c) {
  console.log(c);
})

// 解释为 function (x) { return x }(a++)
// 即调用匿名函数,结果f等于0
var a = 0;
var f = function (x) { return x }
(a++)

Only the end of the beginning of the next line with the Bank, can not be put together to explain, JavaScript engine will automatically add a semicolon.

if (a < 0) a = 0
console.log(a)

// 等同于下面的代码,
// 因为 0console 没有意义
if (a < 0) a = 0;
console.log(a)

Further, if the first is a line of "self-energizing" ( ) ++or "decrement" ( ) --operator, it is automatically added in front thereof a semicolon.

a = b = c = 1

a
++
b
--
c

console.log(a, b, c)
// 1 2 0

The reason why the above code will be 1 2 0the result, because the increment and decrement operators before, automatically add the semicolon. The above code is virtually identical to the following form.

a = b = c = 1;
a;
++b;
--c;

If continue, break, returnand throwbehind these four statements directly with line breaks, it will automatically add a semicolon. This means that if returnthe statement is literal return of an object, first of braces must be written on the same line, otherwise not get the expected results.

return
{ first: 'Jane' };

// 解释成
return;
{ first: 'Jane' };

Due to explain the behavior of the engine automatically add a semicolon is difficult to predict, and therefore preparation of the code should not omit the semicolon the end of the line.

Should not omit the semicolon at the end, there is a reason. Some JavaScript code compressor (uglifier) ​​does not automatically add a semicolon, and therefore there is no semicolon at the end of the encounter, it will allow the code to maintain the status quo, rather than compressed into one line, so that the compression can not get optimal results.

In addition, do not write the end of the semicolon, the merger could lead to script errors. So, some code base before the start of the first statement, will add a semicolon.

;var a = 1;
// ...

The wording of the above can be avoided when combined with other script, the last line of the statement is not standing in the front of the semicolon, causing problems run error.

Global Variables

The biggest drawback grammar JavaScript, probably a global variable for any block of code is readable and writable. This modular and reusable code, very negative.

It is therefore recommended to avoid using global variables. If you had to use, consider the variable name in capital letters represent, it is easier to see that this is a global variable, for example UPPER_CASE.

Variable declaration

JavaScript will automatically variable declaration "lift" (hoist) to the head block (block) of.

if (!x) {
  var x = {};
}

// 等同于
var x;
if (!x) {
  x = {};
}

This means that the variable xis ifexisted before the code block. To avoid potential problems, it is best to variable declarations at the head of the code block.

for (var i = 0; i < 10; i++) {
  // ...
}

// 写成
var i;
for (i = 0; i < 10; i++) {
  // ...
}

This written above, it is easy to see that there is a global loop variable i.

In addition, all functions should be defined prior to use. Variables declared inside a function, the function should be placed on the head.

with statement

withYou can reduce the write code, but confusing.

with (o) {
 foo = bar;
}

The above code, can have four operating results:

o.foo = bar;
o.foo = o.bar;
foo = bar;
foo = o.bar;

These four results are possible, depending on whether there are different definitions of variables. Therefore, do not use the withstatement.

Equal and strictly equal

JavaScript has two equal operators expressed: "equal" ( ==) and "stringent equal" ===( ).

Equality operator will automatically convert variable types, resulting in a lot of unexpected situations.

0 == ''// true
1 == true // true
2 == true // false
0 == '0' // true
false == 'false' // false
false == '0' // true
' \t\r\n ' == 0 // true

It is therefore recommended not to use the equality operator ( ==), only the strict equality operator ( ===).

Consolidated statement

Some programmers pursuit of simplicity, like merge statement for different purposes. For example, the original sentence is

a = b;
if (a) {
  // ...
}

He likes to be written as follows.

if (a = b) {
  // ...
}

Although the statement is missing a line, but greatly reduced readability, but will also cause misunderstanding, let others misunderstood the meaning of this line of code is below.

if (a === b){
  // ...
}

It is not recommended for different purposes statement, merged into one line.

Increment and decrement operators

Increment ( ++) and decrement ( --) operator, in front of or behind the variable, the value returned is not the same, it is prone to error. In fact, all of the ++operators can be used += 1instead.

++x
// 等同于
x += 1;

Instead += 1, the code becomes more clear.

Recommendation increment ( ++) and decrement ( --) operator to make use of +=and -=replaced.

switch ... case structure

switch...caseStructural requirements, in each caseof the last line must be a breakstatement, otherwise it will then run to the next case. This is not only easy to forget that it will result in a lengthy code.

Also, switch...casedo not use braces, is not conducive to a unified code form. In addition, this structure is similar to gotothe statement, the program flow is likely to cause confusion, making the code structure chaotic, inconsistent with the principle of object-oriented programming.

function doAction(action) {
  switch (action) {
    case 'hack':
      return 'hack';
    case 'slash':
      return 'slash';
    case 'run':
      return 'run';
    default:
      throw new Error('Invalid action.');
  }
}

The above code is rewritten into the object structure recommendations.

function doAction(action) {
  var actions = {
    'hack': function () {
      return 'hack';
    },
    'slash': function () {
      return 'slash';
    },
    'run': function () {
      return 'run';
    }
  };

  if (typeof actions[action] !== 'function') {
    throw new Error('Invalid action.');
  }

  return actions[action]();
}

Therefore, the proposed switch...casestructure can be replaced with the object structure.

Reference links

Guess you like

Origin www.cnblogs.com/wbyixx/p/12497556.html