To write JavaScript code, you must follow certain programming specifications. The following are the JS language specifications of Google, which are directly translated (refer to the original English version ). 1. Variable: In most cases, use var to declare that if var is not displayed, the variable will be attached to the global context and may be cited as... SyntaxHighlighter. all ();
To write JavaScript code, you must follow certain programming specifications. The following are the JS language specifications of Google, which are directly translated (refer to the original English version ).
1. Variable: use var declaration in most cases.
If var is not displayed, the variable will be attached to the global context, which may cause a conflict of names. Moreover, without using var declaration, it is difficult to distinguish the scope of the variable (for example, it may be attached to a Document or Window object or a local variable ). In most cases, var is used to declare variables.
Of course, if you apply for a variable that only belongs to a certain "class", do not use var. For example, if jQuery (version 1.6.4) contains row 41st of jQuery, attributes must be added to the jQuery object, so var cannot be used for declaration.
2. Constant: Use the NAME_LIKE_THIS naming method, use @ const as appropriate, and do not use the const keyword.
This naming method is sufficient for simple "non-reference" types. For example:
Js Code
/**
* The number of seconds in a minute.
* @ Type {number}
*/
Goog. example. SECONDS_IN_A_MINUTE = 60;
For the "Reference" type, use the @ const annotation. For example:
Js Code
/**
* The number of seconds in each of the given units.
* @ Type {Object. }
* @ Const
*/
Goog. example. SECONDS_TABLE = {
Minute: 60,
Hour: 60*60
Day: 60*60*24
}
This ensures that the compiler guarantees the meaning of constants.
Do not use the const keyword because IE does not support it.
3. semicolon: used.
The explicit use of semicolons may cause problems that are hard to detect. In particular:
Js Code
// 1.
MyClass. prototype. myMethod = function (){
Return 42;
} // There is no semicolon
(Function (){
// Initialize some variables with the scope of this anonymous Function
})();
Var x = {
'I': 1,
'J': 2
} // There is no semicolon
// 2.
[NormalVersion, ffVersion] [isIE] ();
Var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // No semicolon
// 3.
-1 = resultOfOperation () | die ();
What happened?
First: JS error-first, the function that returns 24 will be executed, because there is a parentheses next to it and the parameter is a function. Then the returned value 42 is called and an error occurs.
Second, you are very likely to get a "no such property in undefined" error during execution, because the Function x [ffVersion] [isIE] () is actually being executed.
Third, the die function is assigned the return value of die () only when resultOfOperation () is NaN and THINGS_TO_EAT is.
Why?
JS syntax requires a statement to end with a semicolon unless the position of the semicolon can be safely inferred. In the preceding example, function declaration, object declaration, and array are used in a statement. The symbols like "}" and "] are insufficient to prove the end of the statement. If the next character is an operator or "{", "[", then JS considers that the statement has not ended.
This write error is surprising, so make sure that the assignment statement ends with a semicolon.
4. nested functions: available
Nested functions are very useful, for example, when creating continuous tasks or hiding tool functions. Don't worry, use it.
5. Declare a function in the language block: Do not use it!
Do not write the following code:
Js Code
If (x ){
Function ff (){}
}
Although most script engines support this function declaration method, this is not in the ECMAScript standard. ECMAScript only supports function declaration in the root statement. If needed, you can use variables to save this function. As follows:
Js Code
If (x ){
Var ff = function (){}
}
6. Exception: available
If it is not written from 0, the exception cannot be avoided, such as when using the program development framework.
7. custom exception: available
If there is no custom exception, a function can return both normal values and an error message, which is confusing. The less elegant solution includes the reference type of the returned execution error message and the returned objects containing potential errors. These are ancient exception handling methods. Therefore, you can use custom exceptions when appropriate.
8. Standard features: use standard features instead of non-standard features
To maximize portability and compatibility. For example, you can use string. charAt (4) instead of string [4]. To access elements, you must use DOM letters instead of a specific project name.
9, for the original type packaging: Do not use!
There is no need to package the original type, and the packaging is very error-prone, as shown below:
Js Code
Var x = new Boolean (false );
If (x ){
Alert ('Hi'); // will execute
}
Do not do this!
However, type conversion is acceptable.
Js Code
Var x = Boolean (0 );
If (x ){
Alert ('Hi'); // do not execute
}
Typeof Boolean (0) = 'boolean ';
Typeof new Boolean (0) = 'object ';
This feature is particularly useful when converting objects into numbers, strings, and boolean.
10. Multi-level prototype hierarchy: Not recommended
A multilevel prototype hierarchy can be used to implement inheritance. It is difficult to maintain a multi-level prototype.
(This is my opinion)
11. method definition: Foo. prototype. bar = function (){};
Although there are several ways to bind methods and attributes to a class, this is the best practice.
12. Closure: it can be used, but be careful!
Closures may be the most useful and abuse feature of JavaScript.
However, remember that a closure holds a reference to its closure range. If a closure is assigned to a DOM element, it may cause loop reference, resulting in Memory leakage, such:
Js Code
Function foo (element, a, B ){
Element. onclick = function () {/* use a and B */
}
The closure of the function itself references element, a, and B, even if it never used element; Because element also saves reference pointing to the closed package, it forms a ring, cannot be recycled by GC. In this case, you can:
Js Code
Function foo (element, a, B ){
Element. onclick = bar (a, B );
}
Function bar (a, B ){
Return function () {/* use a and B */}
}
13, eval (): used only for deserialization
Eval () can cause confusing semantics, and it is dangerous to include user input strings. There is usually a better way to write the code for this requirement, so it is usually not used. However, eval makes deserialization very simple, so it is acceptable.
Deserialization is a process of converting a series of characters into a memory data structure. For example, you may write the following objects to a file:
Js Code
Users = [
{},
{},
...
];
To read this object into memory, you can use eval.
Similarly, eval can simplify the task of decoding RPC return values. For example:
Js Code
Var userOnline = false;
Var user = 'nsrat ';
Var xmlhttp = new XMLHttpRequest ();
Xmlhttp. open ('get', 'HTTP: // chat.google.com/isUserOnline? User = '+ user, false );
Xmlhttp. send ('');
// Server returns:
// UserOnline = true;
If (xmlhttp. status = 200 ){
Eval (xmlhttp. responseText );
}
// UserOnline is now true.
14, with () {}: do not use!
Using with will make the code more confusing. Because the objects in with may have attributes that conflict with local variables, the original meaning of the program may change completely. For example:
Js Code
With (foo ){
Var x = 3;
Return x;
}
The local variable x may conflict with the property of foo. If the property of foo has a setter, other code may be executed. Therefore, do not use!
15. this: only when constructing functions, methods, and closures
Using this is easy to make people confused. This can point to a global object (window), a caller, a DOM node, a newly created object, or another object (if the method is called by call or apply ).
Because this is prone to errors, the restrictions apply to the following situations:
Constructor
Object methods (including creating closures)
16, for-in Loop
The for-in loop is often used to traverse elements in the Array. The error is that it not only traverses the elements from 0 to length-1, but also traverses the prototype chain. The following are several errors:
Js Code
Function printArray (arr ){
For (var key in arr ){
Print (arr [key]);
}
}
PrintArray ([0, 1, 2, 3]); // This works.
Var a = new Array (10 );
PrintArray (a); // This is wrong.
A = document. getElementsByTagName ('*');
PrintArray (a); // This is wrong.
A = [0, 1, 2, 3];
A. buhu = 'wine ';
PrintArray (a); // This is wrong again.
A = new Array;
A [3] = 3;
PrintArray (a); // This is wrong again.
Therefore, we need to use normal traversal.
17. array: Do not use arrays as map, hash, or union arrays.
Non-numeric indexes are not allowed for arrays. If you need non-numeric indexes, you can use objects. Array is acceptable because Array inherits from Object.
18. Multi-line string: Do not use
Do not:
Js Code
Var myString = 'a rather long string of English text, an error message \
Actually that just keeps going and going -- an error \
Message to make the Energizer bunny blush (right through \
Those Schwarzenegger shades )! Where was I? Oh yes ,\
You \ 've got an error and all the extraneous whitespace is \
Just gravy. Have a nice day .';
The spaces at the beginning of each line cannot be safely skipped during compilation; the spaces at the end of \ may also cause inexplicable errors. Moreover, this syntax is not supported in ECMAScript.
Add strings:
Js Code
Var myString = 'a rather long string of English text, an error message '+
'Actually that just keeps going and going -- an error' +
'Message to make the Energizer bunny blush (right through '+
'Those Schwarzenegger shades )! Where was I? Oh yes, '+
You \ 've got an error and all the extraneous whitespace is '+
'Just gravy. Have a nice day .';
19. Literal array and object: it is recommended to use
The constructor is usually replaced by literal arrays and objects.
The Array constructor fails due to improper parameters.
Js Code
// Length is 3.
Var a1 = new Array (x1, x2, x3 );
// Length is 2.
Var a2 = new Array (x1, x2 );
// If x1 is a number and it is a natural number the length will be x1.
// If x1 is a number but not a natural number this will throw an exception.
// Otherwise the array will have one element with x1 as its value.
Var a3 = new Array (x1 );
// Length is 0.
Var a4 = new Array ();
For this reason, if someone changes the code and transmits a parameter instead of two parameters, the Code may deviate from the original intent.
To avoid this situation, we can:
Js Code
Var a = [x1, x2, x3];
Var a2 = [x1, x2];
Var a3 = [x1];
Var a4 = [];
Although the Object constructor does not have this problem, we recommend that you use a literal Object for readability and coherence. For example:
Js Code
Var o = {};
Var o2 = {
A: 0,
B: 1,
C: 2,
'Strange key': 3
};
20. Change the prototype of the built-in object: forbidden!
Changing the prototype of a built-in object is strictly forbidden.
Author: "Technical enthusiasts"