JavaScript mode (2): Basic Skills

Source: Internet
Author: User

The consequence of using as many global variables as possible

After a global variable is created, it will be shared throughout the JavaScript Application and Web page. All global variables exist in a global namespace and are prone to conflicts.

Unconsciously, a global variable is created.

The reason is that JavaScript has two features: the first is that JavaScript can directly use variables without declaration, and the second is the concept of global variables implied by JavaScript, that is, if any variables are not declared, all

To avoid accidental creation of global variables, we can use var to declare variables.

Another anti-pattern for creating implied global variables is chained assignment with var declarations.

The reason for the above result is that the priority of the JavaScript operator from right to left is as follows:

 a = (b = 0);

The solution is simple: assign values to all variables assigned by the chain, as shown in the following code:

= b = 0
Another reason to avoid the large use of global variables is code porting. Your code runs in the current environment (host), but in another environment, global variables may conflict with variables in other environments. Release of global variables

The implication is that global variables are slightly different from clearly defined global variables. The difference is whether delete can be used to destroy them. The Code is as follows:

The code above indicates that the global variables can be deleted through delete, while the var definition cannot.

Access global variables

In a browser, global variables can be accessed anywhere in the Code through the window attribute, but it may also happen unexpectedly (a local variable named window is declared ).

In other environments (such as NodeJS), window is not called window. In NodeJS, the global variable for the entire Runtime period is global, and the use of window is not rigorous enough.

The solution code is as follows:

 global = ( 

Generally, global objects can be obtained in this way, because this is called as a function inside the function (not created by the constructor or by calling or applying), and usually points to global objects.

However, if your code runs in the strict mode of ES5, it cannot be used as follows:

Variable and function declaration elevation JavaScript allows multiple variables or functions to be declared anywhere in the function. Declaration at the top of the function is equivalent to Declaration at the top of the function.

The code above demonstrates that var v1 is regarded as a declaration of a local Variable, so the output is undefined, which actually involves a Variable Object, when printing, he will first find it in the Variable Object. If he cannot find it, he will find it in the window. If he finds it, he will print it directly.

From the optimization of the for loop, you may find it strange. Is there anything else you can optimize the for loop? Not optimization, but some notes

Let's talk a little bit about the Code:

( i = 0; i < array.length; i++}

The problem with this mode is that the length of the array needs to be accessed in each loop. If the array is good, the impact is not very great (the speed is slow ). However, if we traverse a DOM set, we know that it is very performance-consuming to operate the DOM under the document, and if we save the length with a variable, this avoids DOM query in every loop, which greatly reduces the performance consumption in all browsers. The speed in safari is increased by three times, and that in IE7 is increased by 170 times.

Another improvement can be achieved through:

 array = [],len =(len,len--}

This mode has two advantages: the minimum variable is used and gradually reduced to 0, because the same 0 is faster than the same Array length.

There is also a while mode. similar to this, I will not post code ()

Don't add the prototype of the built-in object. I used to like to write this type of code. I was reminded by my wise "Hui ge" to look at the typical anti-pattern... Under self-review

Adding a built-in Constructor (Object, Array, Function) prototype is very nice (the pitfall will be entered sooner or later ..), However, this may seriously affect maintainability, because it will make your code more unpredictable. For example, if you overwrite the Array slice method, other engineers do not know, he cannot get the expected results (more serious than the global object pollution). If he must write the results, he must first accurately record the results and communicate with the team clearly.

Some small details should be avoided to avoid implicit type conversion

JavaScript performs implicit type conversion when executing a comparison Statement, which is also why the comparison statement false = 0 or "" = 0 returns true.

To avoid Ambiguity Caused by implicit conversions, it is best to use = and! ===

Avoid using eval ()

Eval executes any string as JavaScript code (an error is reported when eval is used in strict ES5 mode), and eval executes the modified Code (possibly modified by the client ), may cause some security risks

The alternative scheme of eval uses the method provided by the browser to parse JSON request. parse (). For classes that do not support parse, you can use class libraries from JSON.org, and pass parameters through the setTimeout, setInterval, and function constructor, in most cases, eval-like risks may also occur, as shown in the following code:

setTimeout("func()" , 1000"func(1,2,3)" , 1000setTimeout(func , 10001,2,31000);

If the pass to setTimeout is a string, JavaScript will still execute the passed string in the way of program code. If you must use eval, you can use the new Function () method to replace eval, the Code is as follows:

 code = "console.log(5)" Function(code)(); 
Use the second parseInt Parameter

We usually ignore the second parameter, but sometimes some bugs occur. For example, if the string I uploaded starts with 0, an error will occur, he will not be sure whether it is 8 or 10, so it is best to add the above. In addition, it is faster to convert a string to a value. The Code is as follows:

+ “08” Number(“08”) 

These methods are much faster than parseInt, and parseInt is parsed rather than simple conversion. For example, if "08 soso" is input, all other methods except parseInt will return NaN

Run JSLint

JSLint can check your code and find out in advance the shortcomings of your code. After writing the code, you can run it again on JSLint. This is a good programming mode (the BUG cannot be hurt)

Postscript:

For the first time I wrote such a long blog, there are inevitable errors in the text. If you can point out gratitude

Some of the Reading Notes have been added to my work needs for understanding. If something is wrong, please contact me to make progress together.

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.