Javascript programming style

Source: Internet
Author: User
DouglasCrockford is Javascript authority, and the Json format is his invention. In last November, he gave a speech (Youtube) about the good Javascript programming style. I highly recommend this speech. It not only helps you learn Javascript, but also makes you feel comfortable, because... SyntaxHigh

Douglas Crockford is Javascript authority, and the Json format is his invention.
In last November, he gave a speech (Youtube) about the good Javascript programming style.
I highly recommend this speech. It not only helps you learn Javascript, but also makes you feel comfortable, because Crockford is humorous and occasionally makes the audience smile.
Next, I will summarize the "Javascript programming style" based on the speech and the code specifications written by Crockford ".
The so-called programming style refers to the style rules for coding. Different programmers often have different programming styles.
Some people say that the specification of the compiler is called "grammar", which must be followed by programmers. What the compiler ignores is programming style ), this is something programmers can choose freely. This statement is not completely correct. Programmers are free to choose a programming style, but a good programming style helps to write programs with higher quality, fewer errors, and easier maintenance.
Therefore, it should be clear that the choice of "programming style" should not be based on personal interests, familiarity, typing workload and other factors, but should consider how to make the code clear and easy to read, reduce errors. What you choose is not a style you like, but a style that clearly expresses your intent. This is especially important for languages with high syntax freedom and immature design.
I. Location of braces
Most programming languages use braces ({}) to represent blocks ). There are many different ways to write the braces.
There are two most popular ones. One is that the braces start with another line:
Block
{
...
}
The other is that the braces are followed by the keywords:
Block {
...
}
Generally, both write methods are acceptable. However, Javascript requires the latter type, because Javascript automatically adds a semicolon at the end of the sentence, leading to some imperceptible errors.
Return
{
Key: value;
};
The original intention of the above Code is to return an object, but the returned result is actually undefined, because Javascript automatically adds a semicolon after the return statement. To avoid such errors, you must write the following:
Return {
Key: value;
};
Therefore,
Rule 1: braces in the beginning of the block. Do not create another line.
2. parentheses
Parentheses has two functions in Javascript: one for calling a function and the other for grouping ). We can use spaces to distinguish the two different brackets.
Rule 2: When a function is called, there is no space between the function name and the left bracket.
Rule 3: there is no space between the function name and the parameter sequence.
Rule 4: there is a space between all other syntax elements and the left parenthesis.
According to the above rules, the following statements are not standardized:
Foo (bar)
Return (a + B );
If (a = 0 ){...}
Function foo (B ){...}
Function (x ){...}
3. semicolon
A semicolon indicates the end of a statement. In most cases, if you omit the semicolon at the end of a sentence, Javascript will automatically add it.
Var a = 1
Equivalent
Var a = 1;
Therefore, it is recommended that you skip the last semicolon. However, if the first character (token) in the next line is one of the five characters below, Javascript will not add a semicolon at the end of the last line: "(", "[", "/", "+", and "-".
X = y
(Function (){
...
})();
The above code is equivalent
X = y (function (){...})();
Therefore,
Rule 5: Do not omit the semicolon at the end of the sentence.
4. with statement
With can reduce code writing, but can cause confusion.
With (o ){
Foo = bar;
}
The above code can have four running results:
O. foo = bar;
O. foo = o. bar;
Foo = bar;
Foo = o. bar;
All four results may occur, depending on whether different variables are defined. Therefore,
Rule 6: Do not use the with statement.
5. Equality and strict equality
Javascript has two operators for "equal": "equal" (=) and "strictly equal" (= ).
The "equal" operator will automatically convert the variable type, resulting in many unexpected situations:
0 = ''// true
1 = true // true
2 = true // false
0 = '0' // true
False = 'false' // false
False = '0' // true
"\ T \ r \ n" = 0 // true
Therefore,
Rule 7: Do not use the "Equal" (=) operator, only use the "strictly equal" (=) operator.
6. Statement merging: www.2cto.com
Some programmers pursue conciseness and prefer to merge statements for different purposes. For example, the original statement is
A = B;
If (){...}
He prefers to write it as follows:
If (a = B ){...}
Although the statement has one row missing, the readability is greatly reduced, and it may cause a misunderstanding, which makes others mistakenly think that the meaning of this line of code is:
If (a = B ){...}
In another case, some programmers prefer to assign multiple variables to the same row:
Var a = B = 0;
He thinks this line of code is equivalent
Var a = 0, B = 0;
Actually not. The real effect is as follows:
B = 0;

Var a = B;
Therefore,
Rule 8: Do not merge statements for different purposes into one row.
7. Variable Declaration
Javascript automatically declares the variable to the header of the block.
If (! O ){
Var o = {};
}
Equivalent
Var o;
If (! O ){
O = {};
}
To avoid possible problems, we recommend that you put all the variable declarations in the header of the code block.
For (var I ...){...}
It is best to write:
Var I;

For (I ...){...,}
Therefore,
Rule 9: all variable declarations are placed in the function header.
Rule 10: All functions are defined before use.
8. Global Variables
The biggest syntax disadvantage of Javascript is that global variables are readable and writable for any code block. This is very unfavorable for code modularization and reuse.
Rule 11: Avoid using global variables. If you have to use them, use uppercase letters to indicate the variable name, such as UPPER_CASE.
9. new command
Javascript uses the new command to generate a new object from the constructor.
Var o = new myObject ();
The problem with this approach is that once you forget to add the new, myObject () Internal this keyword will point to the global object, so that all the variables bound to this will become all variables.
Rule 12: Do not use the new command. Use the Object. create () command instead.
If you have to use new, it is best to visually distinguish the constructor from other functions to prevent errors.
Rule 13: name of the constructed function. The first letter is capitalized (InitialCap). Other function names are all in lowercase.
10. Auto-increment and auto-subtraction Operators
The auto-increment (++) and auto-increment (--) operators are placed before or after the variable. The returned values are different and errors are easy to occur.
In fact, all ++ operators can be replaced by "+ = 1.
++ X
Equivalent
X + = 1;
The Code becomes clearer. There is a ridiculous example where the source code of a Javascript function library contains the following snippet:
++ X;
++ X;
This programmer forgot to write a simpler and more reasonable statement:
X + = 2;
Therefore,
Rule 14: Do not use the auto-increment (++) and auto-Subtract (--) operators, instead of the + = and-= operators.
11. Block
If the code body for loop and judgment has only one line, Javascript allows this block to omit braces.
The following code
If (a) B (); c ();
The original intention may be
If (a) {B (); c ();}
However, the actual effect is
If (a) {B ();} c ();
Therefore,
Rule 15: Always use braces to represent blocks.
(End)


From justjavac)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.