Key points for writing high quality JavaScript code in Xin Xing's notes, Xin Xing's javascript

Source: Internet
Author: User

Key points for writing high quality JavaScript code in Xin Xing's notes, Xin Xing's javascript

First this article is http://www.zhangxinxu.com/wordpress? P = 1173 Reading Notes. Readers can read the original text in the space of Xin Xu. I have simplified it here.

Maintenance code requirements:

(1) readable (2) consistent (3) predictable

(4) It looks like a record written by the same person (5)


Principle 1: Minimum global variables

JavaScript acts on it through function management. The variable value declared in the function is inside the function and is unavailable outside the function. The global variables are declared outside any function, or they are directly used without being declared.

Each js environment has a global object, which can be accessed when this is used outside any function. Each global variable we create becomes the attribute of this global object. In the browser, for convenience, this global object has an additional attribute called window, and this window object only wants the global object itself.

The following code shows how to create and access global variables in a browser. Of course this is not recommended:

Xin = "hello ";

Console. log (xin );

Console. log (window. xin );

Console. log (window ['sin']);

Console. log (this. xin );

But the problem with global variables is that our js applications and all the code on the Web page share these global variables, but they are in the same global namespace, therefore, when two different parts of the program define global variables with the same name but different roles, naming conflicts are inevitable.

Web page inclusion is not the code written by the page developer. For example:

(1) third-party JavaScript Library

(2) AD script code

(3) third-party User tracking and analysis code

(4) Different Types of widgets, such as buttons

To be compatible with other scripts, it is important to use as few global variables as possible. The common strategy to reduce global variables is to use the namespace mode or the function is automatically executed immediately. If you want to use global variables, we recommend using var to declare variables.

Because of the two features of JavaScript, it is very easy to unconsciously create global variables. These two features are:

(1) variables can be used without declaration.

(2) JavaScript has an implicit global concept, which means that any variable we do not declare will become a global object attribute.

For example, function sum (x, y) {result = x + y; return result;} declares a global variable.

For example, in function foo () {var a = B = 0;}, a is a local variable, but B is a global variable.

When we use the task chain for partial var declaration, it is possible to create an implicit global variable.


Principle 2: Pay attention to the for Loop

In the for loop, We Can cyclically obtain the values of arrays or arrays similar to objects, such as arguments and HTMLCollection objects. The general loop form is as follows:

For (var I = 0; I <myarray. length; I ++ ){

// The operation on myarray [I]

}

The disadvantage of the above loop is that the length of the array needs to be obtained during each loop, which will reduce the performance of our code. In particular, myarray is not an array, but an HTMLCollection object.

HTMLCollection is an object returned by the DOM method, for example:

Document. getElementsByName ()

Document. getElementsByClassName ()

Document. getElementsByTagName ()

There are also some other htmlcollections which were introduced before the DOM standard and are still in use, such:

Document. images: All image elements on the page

Document. links: All a tag elements on the page

Document. forms: All forms on the page

Document. forms [0]. elements: all fields in the first form on the page

The trouble with collections is that they query Basic Documents (html pages) in real time, which means that every time we access the length of any set, we need to query the dom in real time, and dom operations are generally expensive.

Therefore, when we use a loop to obtain the value, the length of the cached array (or set) is better. The code below:

For (var I = 0, max = myarray. length; I <max; I ++ ){

// Other operations

}

We can do this using the single var form:

Function logoff (){

Var I = 0,

Max,

Myarray = [];

For (I = 0, max = myarray. length; I <max; I ++ ){

// Other operations

}

}

We usually apply the for-in loop to the traversal of non-array objects. Using for-in for loop is also called "enumeration ". although we can also use the for-in loop array, because arrays in js can also be seen as objects, it is not recommended. Because logical errors may occur if the array object has been enhanced by custom functions. In addition, the order of the attribute list in for-in cannot be guaranteed. It is best to use a normal for loop for arrays and a for-in loop for objects.

Principle 3: do not extend the built-in prototype

Expanding the prototype attribute of constructor is a powerful method, but sometimes it is too powerful. If we add a built-in constructor, such as Object (), Array (), or Function (), it will seriously reduce maintainability because it makes our code unpredictable.

Principle 4: Use a clearer switch

The following switch format is recommended:

Var inspect_me = 0,

Result = '';

Switch (inspect_me ){

Case 0:

Result = "zero ";

Break;

Case 1:

Result = "one ";

Break;

Default:

Result = "unknown ";

}

In the above example, the style rules are as follows:

(1) alignment of each case and switch, except for the indentation rules in curly brackets

(2) code indent in each case

(3) Each case is cleared with a break.

(4) Avoid penetration, that is, deliberately ignore the break. Generally, we do not recommend that you ignore the break.

(5) End the switch with default


Principle 5: avoid implicit type conversion

JavaScript variables are implicitly converted during comparison. This means that the result returned by false = 0 or "" = 0 is always true. To avoid confusing implicit type conversion, we need to use = or! = Operator.

 

Principle 6: Avoid eval ()

This method receives arbitrary strings and processes them as JavaScript code. If the code is dynamically generated at runtime, we usually do not use eval. For example, we can use square brackets to access dynamic attributes.

No recommended code before the change:

Var property = "name ";

Alert (eval ("obj." + property ));

Recommended code after the change:

Var property = "name ";

Alert (obj [property]);

It is equally important to pass a string to setInterval (), setTimeout (), and Function () constructors. In most cases, this is similar to eval (), so avoid it. Behind the scenes, JavaScript still needs to evaluate and execute the strings we pass to the program.

No recommended code before the change:

SetTimeout ("myFunc ()", 1000 );

SetTimeout ("myFunc (1000, 3 );

Recommended code after the change:

SetTimeout (myFunc, 1000 );

SetTimeout (function () {myFunc (1000, 3 );

Using the new Function () construction is similar to eval (), so be careful.

Principle 7: Numerical Conversion under parseInt ()

When parseInt () is used, we can obtain the value from the string. This method receives another base parameter, which is often ignored but should not. A problem may occur when the string starts with "0". For example, in ECMAScript 3, a string starting with 0 is processed as an octal string, but it has changed in ECMAScript 5.

However, to avoid conflicts, we recommend that you always specify the base number:

Var month = "06 ",

Year = "09 ";

Month = parseInt (month, 10 );

Year = parseInt (year, 10 );

If we ignore the base parameter, for example, parseInt (year), the returned value is 0, because 09 is treated as an octal value, and 09 is not a valid number in octal.

The replacement method is to convert a string to a Number, including + "08" or Number ("08.


As for naming conventions, it is too crowded to write them into another blog.

Zookeeper

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.