Improve the robustness of javascript programs

Source: Internet
Author: User

Post ed in 2009/07/10 02: 17 H. yongbin

I was born from the control theory. The robustness of a control system is indeed important in system design. What is the robustness of the control system?

The so-called "robustness" means that the control system maintains certain performance characteristics under a certain (structure, size) parameter disturbance (from Baidu encyclopedia ...... Khan ).

In software design and development, we must always consider improving robustness. How to Improve JavascriptProgramWhat about robustness? In my opinion, the robustness of RIA is generally similar to that of JSCodeNormalization is related to Dom operations. Below I will summarize some points of attention during development so that the page will not die and no error will be reported. These things may be trivial in actual development, but it is very critical to improve the overall robustness of the software!

1. Do not use global variables

Alas, I have personally experienced and suffered! In other words, when I modified a page and developed a script, I needed to write cookies. I found that someone referenced a JS file on the page, which contains the setcookie function! The cookie is incorrect. After checking for half a day, I found that another JS file referenced on this page also has a setcookie function. The parameter of the function is different from the one just now, and I guess this function is called! It should have been the previous two colleagues who made their own on the same page. The result is that the function name is the same, and both functions are global! Imagine joining two people to create a global var I = 0; isn't that crazy.

The lessons learned from this story are, of course, that developers of the same team should be compatible with each other and work together. Second, when there are many page JS files, you must have a good level to avoid global variables. One way to avoid global variables is namespace. For example, create a program structure like this:

1:VaRMy_project = {
 
2:DOM :{
 
3:Get:Function(){},
 
4:Make:Function(){}// Etc.
 
5:},
 
6:COOKIE :{
 
7:Get:Function(){},
 
8:Set:Function(){},
 
9:Remove:Function(){}
 
10:},
11: 
 
12:Util :{
 
13:// Some projects utilities
 
14:}
 
15:}

2. Use short circuit expressions

The global variable part is a bit too much, probably because I have experienced that kind of pain. The short-circuit expression is & |, which is used to improve robustness. Let's take two examples. First, we need to get the nodename of the first node of a div node:

 
1:VaRDIV = Document. getelementbyid ("Div_id");
2:VaRNode_name;
 
3:If(Div & Div. firstchild ){// Before using firstchild, determine whether the DIV exists.
 
4:Node_name = div. firstchild. nodename;
 
5:}

Secondly, use | to quickly solve some browser compatibility problems:

 
1:// Obtain the cross-browser solution for element text
 
2:VaRTEXT = span. innertext | span. textcontent |"";

In another example, use | to set the default value:

 
1:// Set the default value
 
2:VaRMy_attr = span. getattribute ("My_attr") | Default_value;

3. Before operating the element, first determine its existence

The example in article 2 has been given. Another example:

 
1:VaRInput = Document. getelementsbyname ("Input") [0];
2:If(Input ){
 
3:Target = input. value;
 
4:}

4. Good code indentation and format

Doug crockford, author of broad cirpt: the good parts, analyzed in detail the importance of the code format when giving a speech to Google. For example:

 
1:Return
 
2:{
 
3:Name: Span. nodename,
 
4:Value: Span. innerhtml
 
5:}

The person who writes such code must be c-born. In JS, the consequence is return nothing. JS has an automatic completion mechanism for statements. If return is the same, a semicolon is automatically added at the end, resulting in a return. If you do not pay attention to it, the program has a problem and it is difficult to find the cause. Therefore, we must develop a good habit of code format, and write the left braces and return, if, and function () together. That is:

 
1:Return{
2:// Something
 
3:}

5. Use cross-browser code

When reading and operating the Dom, I thought about browser compatibility everywhere, so that I could not make trouble for myself. For example, only document. getelementbyid is used; nodename is used instead of tagname; advanced selectors such as getelementsbyclassname are not used; ie-only methods such as applyelement, removenode, and swapnode are not used.

In terms of browser compatibility, we strongly recommend the PPK site quirksmode.org. PPK has tested various browsers and has worked very well. It is our example!

6. Define variables as soon as possible

The scope of JavaScript variables is the entire function. When writing code, if the variables are defined when you want to use them, it is easy to manage them. When developing a program with complicated logic, it is very easy to confuse, and even the variable name is duplicated.

7. Be careful with nodelist

Nodelist, that is, the node list, is a trap. It is not static, but a dangerous dynamic structure. It immediately reflects the changes in the document. A typical endless loop case:

 
1:VaRLis = ul. getelementsbytagname ("Li");
 
2:For(VaRI = 0; I <Lis. length; I ++ ){
3:Ul. appendchild (LIS [I]. clonenode (True));
 
4:}

In the above Code, the length of these Li is not fixed, but changes with the change of Dom. I have experienced this error once, but it is not an endless loop. Take UL and Li for example. I want to delete all Li resources under a UL. The code is similar to the following. Can you see what's wrong?

1:VaRLis = ul. getelemenetsbytagname ("Li");
 
2:For(VaRI = 0; I <Lis. length; I ++ ){
 
3:Ul. removechild (LIS [I]);
 
4:}

8. Use = and! =

Some people may ask why I use =. Why? So I want to ask, since ==== is more rigorous, there is no type conversion, and ==== is full of traps, why not ====? Are you not confident? Oh, it only shows that your program is unstable and robust.

= Automatic type conversion is performed, and crockford calls it edevil twins. Let's not talk about anything else. Here are several examples:

1:Alert (0 ='');// True
 
2:Alert (False='0');// True
 
3:Alert ('\ R \ N'= 0); // true

9. Do not use

When designing the Javascript language, with is intended to provide shortcuts for some operations, but the design is not good enough. It can be said that it would be better if there is no with in Js. Here is an example of using:

 
1:With (element. Style ){
 
2:Position ="Absolute";
3:Left ="100px";
 
4:Top ="100px";
 
5:}

First, with destroys the variable scope structure of the language. In JS, postion, left, and top should have been changed to global variables. Some people may say that this is the case. I can use with to control the variable scope! Good idea. Javascript 1.7 also introduced the let statement to do this. However, with will have unexpected consequences, for example:

 
1:VaRA ='';
 
2:VaROBJ = {B:'B'};
 
3:With (OBJ ){
 
4:A = B;
 
5:}
 
6:Alert (a); // result:'B'

Here a becomes an external variable again! In addition to this strange thing, the execution speed of the with statement is relatively slow. The conclusion is that do not use with to improve the robustness of the program.

10. Do not use eval

Eval can execute a string as JS Code. Eval is often used by new users, for example:

 
Eval ("Value = obj ."+ Key +";");

In fact, he can:

 
Value = OBJ ["key"];

When Eval is executed, the JS interpreter is enabled to execute this small piece of code, which is much slower. In addition, the program debugging and maintainability are greatly reduced. Eval-like statements include:

 
1:Window. setTimeout ("Var I = 0", 1000 );
2:VaRSum =NewFunction ("X","Y","Return X + Y");

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.