A complete summary of JavaScript Common code writing specifications _javascript Skills

Source: Internet
Author: User
Tags array length logical operators

First, global namespace pollution

Always wrap the code inside an immediate function expression to form a separate module.

Not recommended

var x = ten,
 y = m;
Console.log (window.x + ' + window.y ');

Recommended

;(function (window) {
 ' use strict ';
 var x = ten,
  y = m;
 Console.log (window.x + ' + window.y);
} (window));

Second, the immediate execution function

In the immediate execution function, if it is useful to the global variable should be passed through the variable way, so that the function of immediately executing function in the call, can be called as a local variable, to a certain extent to improve program performance.

And it should be added in the formal parameter of the function immediately, undefined in the last position, because the ES3 undefined can read and write, and if the value changed in the global position undefined , your code may not get the overdue result.

It is also recommended to add a semicolon at the beginning and end of the function immediately to avoid the code that is affected by other people's code when merging.

Not recommended

(function () {
 ' use strict ';
 var x = ten,
  y = m,
  C,
  elem=$ (' body ');
 Console.log (window.x + ' + window.y ');
 $ (document). On (' click ', Function () {

 });
 if (typeof c=== ' undefined ') {
  //Your Code
 }
} ());

Recommended

;(function ($,window,document,undefined) {
 ' use strict ';
 var x = ten,
  y = m,
  C,
  elem=$ (' body ');
 Console.log (window.x + ' + window.y ');
 $ (document). On (' click ', Function () {

 });
 if (typeof c=== ' undefined ') {
  //Your Code
 }
} (Jquery,window,document));

Third, Strict mode

The ECMAScript 5 Strict mode can be activated within the entire script or in a method. It corresponds to different javascript contexts to make more rigorous error checking. Strict mode also ensures that JavaScript code is more robust and runs faster.

Strict mode blocks the use of reserved keywords that are likely to be introduced in the future.

You should enable strict mode in your script, preferably in an independent immediate execution function. Avoiding the use of it in the first line of your script causes all of your scripts to start a rigorous pattern, which may cause problems with some third-party libraries.

Not recommended

' Use strict ';
(function () {

} ());

Recommended

(function () {
 ' use strict ';
} ());

Iv. Declaration of variables

For all variable declarations, we should specify that, var if not specified, an error is made var in strict mode, and that the variables within the same scope should be declared as much as possible var , with multiple variables separated by ",".

Not recommended

function Myfun () {
 x=5;
 y=10;
}

Not fully recommended

function Myfun () {
 var x=5;
 var y=10;
}

Recommended

function Myfun () {
 var x=5,
  y=10;
}

Comparison and judgment of using band type judgment

is to use the exact comparison operator of = = = To avoid the obsession caused by the forced type conversion of JavaScript in the process of judgment.

If you use the = = operator, the two sides of the comparison must be the same type as the premise of the condition will be valid.

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 = = Undefin ED); True

 var x = {
 valueof:function () {return
  ' x ';
 }
 };

 W.console.log (x = = ' x ');//true

} (Window.console.log));

Recommended

(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);

Vi. logical operation of variable assignment

Logical Operators | | And && can also be used to return Boolean values. If the action object is a non boolean object, then each expression will be judged from left to right. Based on this operation, there is always an expression returned back. This can be used to simplify your code when the variable is assigned.

Not recommended

if (!x) {
 if (!y) {
 x = 1;
 } else {
 x = y;
}}

Recommended

x = x | | y | | 1;

Seven, semicolon

Always use semicolons, because implicit code nesting can cause problems that are difficult to detect. Of course, we have to fundamentally eliminate these problems [1].

The following examples show the dangers of missing semicolons:

1.
MyClass.prototype.myMethod = function () {return
 ;
}//There is no semicolon

(function () {

}) ();

 2.
var x = {
 ' i ': 1,
 ' J ': 2
}//There is no semicolon
//I know this code you may never write, but give an example
[Ffversion, Ieversion][isie ]();

 3.
var things_to_eat = [Apples, oysters, sprayoncheese]//There is no semicolon

-1 = = Resultofoperation () | | die ();

Error results

1. JavaScript error-The function that first returns 42 is called by the parameter in the second function, and the number 42 is also "invoked" to cause an error.

2.80% you will get the ' no such property in undefined ' error hint, because the call in the real environment is this way: Xffversion, Ieversion ().

3.die is always invoked. Because the result of an array minus 1 is Nan, it is not equal to anything (regardless of whether Resultofoperation returns Nan). So the final result is that die () the resulting value will be assigned to Things_to_eat.

function declaration in block of statement

Never declare a function within a block of statements, which is illegal in the strict mode of ECMAScript 5. The function declaration should be at the top level of the scope. In a statement block, however, the function declaration can be converted to a function expression assignment to a variable.

Not recommended

if (x) {
 function foo () {}
}}

Recommended

if (x) {
 var foo = function () {};
}

Nine, do not use the Eval function

eval() Not only is it dangerous to confuse context, there will always be a better, clearer and safer alternative to writing your code, so try not to use a eval function.

X, array and object literal

1. Use arrays and object literals instead of arrays and object constructors. An array constructor makes it easy for a person to make mistakes on its arguments.

Not recommended

Array length 3
var a1 = new Array (x1, x2, x3);
Array length 2
var a2 = new Array (x1, x2);

If the X1 is a natural number, then its length will be X1
//If X1 is not a natural number, then its length will be 1
var a3 = new Array (x1);

var a4 = new Array ();

Because of this, if you change the code parameters from two to one, the array is likely to have unexpected length changes. To avoid this kind of weird situation, always take a readable array literal.

Recommended

var a = [x1, x2, X3];
var a2 = [x1, x2];
var a3 = [X1];
var a4 = [];

2. The object builder does not have a similar problem, but for readability and uniformity, we should use object literals.

Not recommended

var o = new Object ();

var O2 = new Object ();
o2.a = 0;
o2.b = 1;
o2.c = 2;
o2[' strange key ' = 3;

Recommended

var o = {};
var O2 = {
 a:0,
 b:1,
 c:2,
 ' Strange key ': 3
};

Xi. three-dimensional condition judgment (if shortcut method)

Assigns or returns a statement using the ternary operator. Use in simpler situations to avoid use in complex situations. No one is willing to use the 10-line ternary operator to turn their brains around.

Not recommended

if (x = = ten) {return
 ' valid ';
} else {return
 ' invalid ';
}

Recommended

return x = = 10? ' Valid ': ' Invalid ';

12, for Loop

With a For loop, the length of the array is received using a variable, which is beneficial to the efficiency of code execution, rather than having to recalculate the length of the array every time you go through the loop.

Not recommended

for (Var i=0;i<arr.length,i++) {

}

Recommended

for (Var i=0,len=arr.length;i<len,i++) {

}

13. Repeated DOM operations

Repetitive DOM operations, it is necessary to use a variable for receiving, rather than frequent manipulation of the DOM tree, which has a bad effect on performance and code cleanliness and maintainability

Not recommended

$ ('. Mydiv '). Find ('. Span1 '). Text (' 1 ');
$ ('. Mydiv '). Find ('. span2 '). Text (' 2 ');
$ ('. Mydiv '). Find ('. Span3 '). Text (' 3 ');
$ ('. Mydiv '). Find ('. Span4 '). Text (' 4 ');

Recommended

var mydiv=$ ('. Mydiv ');
Mydiv.find ('. Span1 '). Text (' 1 ');
Mydiv.find ('. span2 '). Text (' 2 ');
Mydiv.find ('. Span3 '). Text (' 3 ');
Mydiv.find ('. Span4 '). Text (' 4 ');

Priority should be given to use when jquery .end() available.end()

Recommended

$ ('. Mydiv '). Find ('. Span1 '). Text (' 1 "). End
   (). Find ('. span2 '). Text (' 2 ');
   . End (). Find ('. Span3 '). Text (' 3 ');
   . End (). Find ('. Span4 '). Text (' 4 ');

14. Annotation Specification

When describing annotations, it is recommended that you format and unify the annotation style, as much as possible when writing a comment, rather than what the code does.

Not recommended

Get Order
function Getorderbyid (id) {
 var ordering;
 //...
 return order;
}

Comments for methods should be unified with block-level annotations

Recommended

/**
 * Obtain Order details based on order ID
 * @param {[number]} ID [order ID]
 * @return {[orders]} [Order Details]/
function Getorderbyid (ID) {
 var order;
 //...
 return order;
}

Summarize

JavaScript common code writing specifications summed up to this is basically the end, this article is still very comprehensive, for everyone to use or learn some JavaScript has a certain reference value, I hope that we can help, if you have questions you can message exchange.

Related Article

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.