JavaScript specification for front-end coding style specifications and front-end javascript
JavaScript specification global namespace pollution and IIFE
Always wrap the code into an IIFE (Immediately-Invoked Function Expression) to create an independent and isolated definition domain. This action prevents global namespace contamination.
IIFE also ensures that your code is not easily modified by the code in other global namespaces (I. e. Third-party libraries, window references, undefined keywords that are overwritten, and so on ).
Not recommended
var x = 10, y = 100;// Declaring variables in the global scope is resulting in global scope pollution. All variables declared like this// will be stored in the window object. This is very unclean and needs to be avoided.console.log(window.x + ' ' + window.y);
Recommendation
// We declare a IIFE and pass parameters into the function that we will use from the global space(function(log, w, undefined){ 'use strict'; var x = 10, y = 100; // Will output 'true true' log((w.x === undefined) + ' ' + (w.y === undefined));}(window.console.log, window));
IIFE (function expression executed immediately)
IIFE is used whenever you want to create a new closed definition domain. It not only avoids interference, but also enables the internal to be released immediately after execution.
It is recommended that all script files start with IIFE.
The execution parentheses of the function expression to be executed immediately should be written in outsourcing brackets. Although writing both internally and externally is effective, writing the entire expression looks more like a whole. Therefore, we recommend that you do this.
Not recommended
(function(){})();
Recommendation
(function(){}());
So, use the following code to format your IIFE code:
(function(){ 'use strict'; // Code goes here}());
If you want to reference a global variable or an IIFE variable, you can pass the parameter in the following ways:
(function($, w, d){ 'use strict'; $(function() { w.alert(d.querySelectorAll('div').length); });}(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 IIFE. 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
// Script starts here'use strict';(function(){ // Your code starts here}());
Recommendation
(function(){ 'use strict'; // Your code starts here}());
Variable Declaration
Always usevar
To declare variables. If var is not specified, the variable is implicitly declared as a global variable, which is difficult to control. If no declaration is made, it becomes unclear about the definition fields of the variable (either in Document or Window, or easily in local definition fields ). Therefore, always use var to declare variables.
The advantage of using the strict mode is that when you mistakenly enter the wrong variable name, it can help you locate the error source through the error message.
Do not push
x = 10;y = 100;
Recommendation
var x = 10, y = 100;
Understanding the definition and improvement of the definition domain of JavaScript
In JavaScript, variables and method definitions are automatically upgraded to execution. JavaScript only has function-level definition fields, but does not have block definition fields in many other programming languages. Therefore, you define a variable in a certain statement and loop body of a function, this variable can act on the entire function, not just in this statement or loop body, because their declaration is automatically upgraded by JavaScript.
Let's take an example to find out what this is about:
Original function
(function(log){ 'use strict'; var a = 10; for(var i = 0; i < a; i++) { var b = i * i; log(b); } if(a === 10) { var f = function() { log(a); }; f(); } function x() { log('Mr. X!'); } x();}(window.console.log));
Upgraded by JS
(function(log){ 'use strict'; // All variables used in the closure will be hoisted to the top of the function var a, i, b, f; // All functions in the closure will be hoisted to the top function x() { log('Mr. X!'); } a = 10; for(i = 0; i < a; i++) { b = i * i; log(b); } if(a === 10) { // Function assignments will only result in hoisted variables but the function body will not be hoisted // Only by using a real function declaration the whole function will be hoisted with its body f = function() { log(a); }; f(); } x();}(window.console.log));
Based on the above improvement process, can you understand the following code?
Valid code
(function(log){ 'use strict'; var a = 10; i = 5; x(); for(var i; i < a; i++) { log(b); var b = i * i; } if(a === 10) { f = function() { log(a); }; f(); var f; } function x() { log('Mr. X!'); }}(window.console.log));
As you can see, this confusing and misunderstood code has led to unexpected results. Only good declaration habits, that is, the declaration rules we will mention in the next chapter, can we avoid the risk of such errors as much as possible.
Escalation statement
To avoid misunderstanding caused by automatic upgrade of variables and method definitions described in the previous section and minimize risks, we should manually declare variables and methods. That is to say, all variables and methods should be defined in the first line of the function.
Use only onevar
Keyword declaration. Multiple variables are separated by commas.
Not recommended
(function(log){ 'use strict'; var a = 10; var b = 10; for(var i = 0; i < 10; i++) { var c = a * b * i; } function f() { } var d = 100; var x = function() { return d * d; }; log(x());}(window.console.log));
Recommendation
(function(log){ 'use strict'; var a = 10, b = 10, i, c, d, x; function f() { } for(i = 0; i < 10; i++) { c = a * b * i; } d = 100; x = function() { return d * d; }; log(x());}(window.console.log));
Write the value assignment in the variable declaration as much as possible.
Not recommended
var a, b, c;a = 10;b = 10;c = 100;
Recommendation
var a = 10, b = 10, c = 100;
Always use the comparison judgment with the type judgment
Always use===
Precise comparison operators avoid the troubles caused by the forced type conversion of JavaScript during the judgment process.
If you use===
Operator. The two sides of the comparison must be of the same type.
If you want to know