To standardize javascript code, we should follow the old principle: "doing does not mean doing it ". Global namespace pollution always wraps the code in an immediate function expression to form a unique...
Javascript code specification
We should follow the old principle of code specifications: "doing does not mean doing it ".
Global namespace pollution
Code is always enclosed in an immediate function expression to form an independent module.
Not recommended
var x = 10, y = 100;console.log(window.x + ' ' + window.y);
Recommendation
;(function(window){ 'use strict'; var x = 10, y = 100; console.log(window.x + ' ' + window.y);}(window));Execute function now
InExecute function nowIf it is useful to global variablesExecute function nowWhen calling the function body, it can be called as local variables to improve program performance to a certain extent.
AndExecute function nowThe undefined parameter is added to the final position. This is because undefined in ES3 can be read and written. If you change the undefined value in the global position, your code may not get the result of overdue.
In additionExecute function nowAdd semicolons at the beginning and end to avoid affecting our own code due to the nonstandard code of others during the merger.
Not recommended
(Function () {'use strict '; var x = 10, y = 100, c, elem = $ ('body'); console. log (window. x + ''+ window. y); $ (document ). on ('click', function () {}); if (typeof c = 'undefined') {// your code }}());
Recommendation
; (Function ($, window, document, undefined) {'use strict '; var x = 10, y = 100, c, elem = $ ('body'); console. log (window. x + ''+ window. y); $ (document ). on ('click', function () {}); if (typeof c = 'undefined') {// your code} (jQuery, window, document ));Strict Mode
ECMAScript 5 strict mode can be activated throughout the script or in a single method. It performs more rigorous error checks in different javascript contexts. The strict mode ensures that javascript code is more robust and runs faster.
Strict mode will prevent the use of reserved keywords that may be introduced in the future.
You should enable the strict mode in your script, preferably in an independent immediate execution function. Avoid using it in the first line of your script and cause all your scripts to start the strict mode, which may cause problems with third-party class libraries.
Not recommended
'use strict';(function(){}());
Recommendation
(function(){ 'use strict';}());Variable Declaration
We should specify var for all variable declarations. If var is not specified, an error will be reported in strict mode, and a variable in the same scope should be declared using a var whenever possible, multiple variables are separated by commas.
Not recommended
function myFun(){ x=5; y=10;}
Incomplete recommendation
function myFun(){ var x=5; var y=10;}
Recommendation
function myFun(){ var x=5, y=10;}Comparison and judgment using the belt-type judgment
Always use the = exact comparison operator to avoid the trouble caused by the forced type conversion of JavaScript during the judgment process.
If you use the = Operator, the two sides of the comparison must be of the same type.
Not recommended
(function(w){ 'use strict'; w.console.log('0' == 0); // true w.console.log('' == false); // true w.console.log('1' == true); // true w.console.log(null == undefined); // true var x = { valueOf: function() { return 'X'; } }; w.console.log(x == 'X');//true}(window.console.log));
Recommendation
(function(w){ 'use strict'; w.console.log('0' === 0); // false w.console.log('' === false); // false w.console.log('1' === true); // false w.console.log(null === undefined); // false var x = { valueOf: function() { return 'X'; } }; w.console.log(x === 'X');//false}(window));Logical operations for variable assignment
Logical Operators | and & can also be used to return boolean values. If the operation object is a non-Boolean object, each expression is determined to be true and false from left to right. Based on this operation, an expression is always returned. This can be used to simplify your code when assigning values to variables.
Not recommended
if(!x) { if(!y) { x = 1; } else { x = y; }}
Recommendation
x = x || y || 1;
Semicolon
Always use semicolons, because implicit code nesting can cause imperceptible problems. Of course, we must fundamentally eliminate these problems [1]. The following examples demonstrate the dangers of missing semicolons:
// 1. myClass. prototype. myMethod = function () {return 42 ;}// no semicolon (function () {}) (); // 2.var x = {'I': 1, 'J': 2} // There is no semicolon here // I know this code you may never write, but for example [ffVersion, ieVersion] [isIE] (); // 3.var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // There is no semicolon-1 = resultOfOperation () | die ();
Error result
JavaScript error -- first, the 42 function is returned and called by parameters in the second function. Then, the number 42 is also called, resulting in an error.
In October, you will get the error message "no such property in undefined", because the call in the real environment looks like this: xffVersion, ieVersion ().
Die is always called. Because the result of an array minus 1 is NaN, It is not equal to anything (no matter whether resultOfOperation returns NaN ). Therefore, the final result is that the value obtained after die () is executed will be assigned to THINGS_TO_EAT.
Statement block function declaration
Do not declare a function in the statement block. This is invalid in the strict mode of ECMAScript 5. The function declaration should be at the top level of the scope. However, you can convert a function declaration into a function expression and assign a value to the variable in the statement block.
Not recommended
if (x) { function foo() {}}
Recommendation
if (x) { var foo = function() {};}Do not use eval Functions
Eval () not only obfuscation of context is dangerous, but there will always be another solution that is better, clearer, and safer than this to write your code. Therefore, try not to use eval functions.
Array and object literal Volume 1. array and object literal volume are used instead of array and object constructor. The array constructor can easily make mistakes in its parameters.
Not recommended
// Array length 3var a1 = new Array (x1, x2, x3); // Array length 2var a2 = new Array (x1, x2); // If x1 is a natural number, then its length will be x1 // If x1 is not a natural number, then its length will be 1var a3 = new Array (x1); var a4 = new Array ();
For this reason, if you change the parameter passed by code from two to one, the length of the array is likely to change unexpectedly. To avoid this weird situation, always use the readable array literal.
Recommendation
var a = [x1, x2, x3];var a2 = [x1, x2];var a3 = [x1];var a4 = [];
2. The object constructor does not have similar problems, but we should use the object literal for readability and uniformity.
Not recommended
var o = new Object();var o2 = new Object();o2.a = 0;o2.b = 1;o2.c = 2;o2['strange key'] = 3;
Recommendation
var o = {};var o2 = { a: 0, b: 1, c: 2, 'strange key': 3};Ternary condition judgment (quick if method)
Assign or return a statement using a ternary operator. It can be used in simple cases to avoid complex cases. No one wants to confuse his mind with the 10-line ternary operator.
Not recommended
if(x === 10) { return 'valid';} else { return 'invalid';}
Recommendation
return x === 10 ? 'valid' : 'invalid';
For Loop
In the for loop process, the length of the array is received by a variable, which improves the code execution efficiency, rather than re-calculating the length of the array every time a loop is taken.
Not recommended
For (var I = 0; IRecommendation
For (var I = 0, len = arr. length; I
Repeated dom operations
Repeated dom operations are necessary to use a variable for receiving, rather than frequently operating the dom tree. This has a bad impact on the performance and code cleanliness and maintainability.
Not recommended
$('.myp').find('.span1').text('1');$('.myp').find('.span2').text('2');$('.myp').find('.span3').text('3');$('.myp').find('.span4').text('4');
Recommendation
var myp=$('.myp');myp.find('.span1').text('1');myp.find('.span2').text('2');myp.find('.span3').text('3');myp.find('.span4').text('4');
When jquery. end () is available, use. end () is preferred ()
Recommendation
$('.myp').find('.span1').text('1') .end().find('.span2').text('2'); .end().find('.span3').text('3'); .end().find('.span4').text('4');Annotation Specification
It is recommended that you format and unify the annotation style when describing the annotation. When writing the annotation, try to describe the idea when writing the code, instead of what the code has done.
Not recommended
// Obtain the order function getOrderByID (id) {var order; //... return order ;}
Block-level annotations should be used for method annotations.
Recommendation
/*** Obtain order details based on order id * @ param {[number]} id [order ID] * @ return {[order]} [order Details] */function getOrderByID (id) {var order ;//... return order ;}
The above is JavaScript-summary of the content of common code writing standards. For more information, see the PHP Chinese website (www.php1.cn )!