How to write High-quality JavaScript code (1)

Source: Internet
Author: User
Tags define object expression functions new features variables variable window

The excellent Stoyan Stefanov in his new book ("Javascript Patterns") introduces a number of techniques for writing high-quality code, such as avoiding global variables, using a single var keyword, looping stored lengths, and so on.

This article not only considers how to optimize coding from the code itself, but also from the design phase of the code, including writing API documents, review of colleagues, and using JSLint. These habits can help you write higher-quality, easier to understand, maintainable code (making your code proud of you years later).

Writing maintainable Code

It takes a lot of effort to fix bugs in software. Especially after the code has been released, the cost of maintenance has increased over time. When you find a bug, fix it immediately, and your code is still warm, and you don't need to remember it, because you just wrote it. But when you do other tasks and almost completely forget the code, you need to:

Re-learning and understanding problems

Understand how the code solves the problem

Another problem is that in big projects or in large companies, it is often the person who fixes the bug, not the person who created the bug, and not the person who found the bug. So reducing the time to understand the code is the most important question, whether it's written by yourself or by other members of the team, because we all want to do something new and interesting, instead of maintaining the old code.

Another common problem in development is that it often takes more time to read code than to write code. Sometimes you delve into a problem that can take a whole afternoon to think about coding. The code could work at the time, but as development went on, other things changed a lot, and it was up to you to review and rewrite the code. Like what:

And the bugs are not solved.

Added new features

Programs need to run in a new environment (such as a newly listed browser)

There is a problem with the code

Code needs to be rewritten because it modifies the schema and even uses another language

For these reasons, you may have written a code in the afternoon, which will take weeks to read. So writing maintainable code is critical to the success of the software.

The maintainable code includes:

Readability

Continuity

Predictability

Looks like it was written by a man.

There are documents

Minimizing global variables

JavaScript uses functions to contract scopes. A variable declared inside a function is not visible externally. Therefore, a global variable is a variable declared outside of any function or not declared.

In JavaScript, there is an accessible global object outside of any function, and every global variable you create is an attribute of that object. In the browser, for convenience, the window is usually used to refer to this global variable. The following code shows how to create a global variable:

 
  
  
  1. Myglobal = "Hello"; Antipattern
  2. Console.log (Myglobal); "Hello"
  3. Console.log (Window.myglobal); "Hello"
  4. Console.log (window["Myglobal"]); "Hello"
  5. Console.log (This.myglobal); "Hello

Problems with global variables

The problem with global variables is that he shares all of your code or a page. They are under the same namespace, which usually results in variable name collisions – Two variables with the same name, but they do have different uses.

It is common to introduce some other people's code into some pages, such as:

Third-party JS Library

The script of the advertising partner

Third-party user behavior analysis or statistical scripts

Different components, buttons, etc.

Joining one of the Third-party components defines a global variable: result. Then in your program, you also define a global variable result. This final result will overwrite the result before the point, so that the third party script will stop working.

So, in order to be friendly to other scripts, the less global variables are used in one page, the better. There are a few ways to tell you how to reduce global variables, such as using namespaces or executing anonymous functions, but the best way to avoid global variables is to use the VAR keyword to declare variables.

Because of the two features of JavaScript, it's very simple to create a global variable. First, you can use a variable that is not even declared, and second, in JavaScript, all undeclared variables become an attribute of the global object (like a declared global variable). Take a look at this example:

 
  
  
  1. function sum (x,y) {
  2. result = x + y;
  3. return result;
  4. }

In this code, result is used without being declared, and this code works well, but after calling the function, there is a global variable named cause, which is the root of all the problems.

The solution to this problem is to use VAR:

 
  
  
  1. function sum (x,y) {
  2. var result = x + y;
  3. return result;
  4. }

A bad habit of two is to use chained methods to assign values when declaring variables, at which point A is a local variable, but B becomes a global variable.

 
  
  
  1. function foo () {
  2. var a=b=0;
  3. ....
  4. }

This is because the expression B = 0 executes first, and B is not declared, so B becomes a global variable, and then returns the value 0 of the expression, giving the declared variable a, in other words, as if you were typing:

 
  
  
  1. var a = (b=0);

If you have declared a variable, then this chained assignment is not a problem:

 
  
  
  1. function foo () {
  2. var a,b;
  3. ...
  4. }

Another reason to avoid using global variables is to take into account the portability of the program. If you want your code to work in different environments, using global variables is likely to conflict with global variables in the new system (perhaps in the previous system).

Forget the impact of Var

There is also a difference between global variables declared using VAR and global variables that are not generated using Var:

Global variables created using the Var declaration cannot be deleted

Global variables that are not declared with VAR can be deleted

This means that global variables that are not generated using the Var declaration are not real variables, they are simply properties of the global object. Properties can be deleted by delete, but the variables are not:

 
 
  1. Define three Globals
  2. var global_var = 1;
  3. Global_novar = 2; Antipattern
  4. (function () {
  5. Global_fromfunc = 3; Antipattern
  6. }());
  7. Attempt to delete
  8. Delete Global_var; False
  9. Delete Global_novar; True
  10. Delete Global_fromfunc; True
  11. Test the deletion
  12. typeof Global_var; "Number"
  13. typeof Global_novar; "Undefined"
  14. typeof Global_fromfunc; "Undefined"

In the strict mode of ES5, assigning a value to a variable declared is an error.

Reading Global objects

In the browser, you can read the Global object through the window variable (unless you redefine the window object within the function). But in some environments, it may not be called window, then you can use the following code to get the global object:

 
  
  
  1. var global = (function () {
  2. return this;
  3. })();

This can be obtained because the global object is inside the function, this points to the global object. But this will not work in the strict mode of ES5, you need to fit some other patterns. When you develop your own library, you can encapsulate your code in an immediate function and then pass this as a parameter.

Single var mode

At the top of your code you just use a var keyword, which has the following benefits:

For all the variables you need, you can see them all in one place.

Avoid using an undefined variable

Help you memorize declared variables, reduce global variables

More streamlined code

Writing is simple:

 
  
  
  1. function func () {
  2. var a = 1,
  3. b = 2,
  4. sum = a + B,
  5. MyObject = {},
  6. I
  7. J
  8. function Body ...
  9. }

Multiple variables are declared with a var and a comma. It is also a good practice to assign a default value to a variable at the time of declaration, to avoid some logical errors and to improve the readability of the code. You can also easily guess the use of variables based on the default values of variables when you read the code.

You can also do some actual work when declaring variables, such as Sum = a + B; In addition, when manipulating DOM elements, you can also save references to DOM elements in a variable:

 
  
  
  1. function Updateelement () {
  2. var el = document.getElementById ("result"),
  3. style = El.style;
  4. Do something with El and style ...
  5. }

Misuse of the Var

JavaScript allows you to have multiple var statements inside a function, but it all behaves as if it were declared at the top of the function. This feature causes some strange logic problems when you use a variable and then declare the variable later. For JavaScript, as long as the variable is in the same scope, it is assumed to be declared, even if it is used before the Var statement. Take a look at this example:

 
  
  
  1. myname = "global"; Global variable
  2. function func () {
  3. alert (myname); "Undefined"
  4. var myname = "local";
  5. alert (myname); "Local"
  6. }
  7. Func ();

In this example, you may expect to pop global for the first time, and the second to eject the local. Because the first time there is no use of the Var declaration myname, this is supposed to be a global variable myname, a second declaration, and then alert should be the local value. And the fact is not so, as long as you appear in the function of Var myname, then JS think you in this function declared this variable, but in reading the value of this variable, because the VAR statement has not been implemented, so it is undefined, very strange logic bar. The code above is equivalent to:

 
  
  
  1. myname = "global"; Global variable
  2. function func () {
  3. var myname; Same as-> var myname = undefined;
  4. alert (myname); "Undefined"
  5. myname = "local";
  6. alert (myname); "Local"
  7. }
  8. Func ();

Let's explain this phenomenon, in the parsing of the code, in two steps, the first step is to deal with the declaration of the variable function, which processes the context of the entire code. The second step is to create function expressions and undefined variables when the code is run. In fact, we just assumed the concept, which is not in the ECMAScript specification, but this behavior is often explained in this way.


[1] [2] [3] Next page



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.