14 best tips for writing javascript code _ javascript tips-JS tutorials

Source: Internet
Author: User
Different developers may have different opinions on writing any programming code. But it is always good to refer to. Below are 14 best JS Code compiling skills released by JavascriptToolbox, Sofish translation (1, 2 ). Different developers may have different opinions on writing any programming code. But it is always good to refer to. Below are 14 best JS Code compiling skills from the Javascript Toolbox release.

1. Always use var
In javascript, variables do not have a global range or a function range. Using the var keyword will be the key to keeping the variables concise and clear. When declaring a global or function-level variable, you must always use the pre-var keyword. The following example will emphasize the potential problem of not doing so.

Problems caused by not using Var

var i=0; // This is good - creates a global variablefunction test() { for (i=0; i<10; i++) {  alert("Hello World!"); }}test();alert(i); // The global variable i is now 10!

In the variable function, variable I does not use var to make it a function-level variable. In this example, it references the global variable. It is a lot of practice to always use var to declare global variables, but it is important to use var to define variables within a function range. The following two methods have the same functions:

Correct Function

function test() {var i=0;for (i=0; i10; i++) {alert("Hello World!");}}

Correct Function

function test() {for (var i=0; i10; i++) {alert("Hello World!");}}

2. Feature Detection, not browser Detection
Some code is written to discover the browser version and perform different actions on it based on the client that the user is using. In general, this is a very bad practice. A better way is to use feature detection. Before using an advanced feature that may not be supported by an old browser, first check whether the feature or feature is available in the browser and then use it. It is better to check the browser version separately, even if you know its performance. You can find an article on this topic.

Example:

if (document.getElementById) {var element = document.getElementById('MyId');}else {alert('Your browser lacks the capabilities required to run this script!');}

3. square brackets

When the access is determined by execution or includes the object attributes that cannot be accessed with A. Sign, square brackets are used. If you are not an experienced Javascript programmer, it is good to always use square brackets.

The attributes of an object are accessed by two fixed methods:. and [] square brackets:

. Mark Method

MyObject. property

[] Square brackets

MyObject ["property"]

Use the. Sign. The attribute name is hard code and cannot be changed during execution. Using [] square brackets, the attribute name is a string calculated from the attribute name. A string must be a hard code, a variable, or even a function that calls back the value of a struct string. If an attribute name is generated during execution, square brackets are required. If you have attributes such as value1 ", value2", and value3 ", you want to use the variable I = 2 to access

This can run:

MyObject ["value" + I]

This cannot be:

MyObject. value + I

In some server environments (such as PHP and Struts), the Form is appended with the [] number to indicate that the Form must be treated as an array on the server. In this way, the use of a. Number to reference a field containing the [] number will not be executed, because [] is a syntax that references a Javascript array. Therefore, the [] Mark method is required:

This can run:

Formref. elements ["name []"]

This cannot be:

Formref. elements. name []

[] Square brackets are recommended to indicate that it is always used when it is needed (obviously. When it is not strictly needed, it is a private preference and habit. A good empirical principle is to use the. Mark method to access standard object attributes and the [] square brackets to access the object attributes defined by the page. In this way, document ["getElementById"] () is a perfect and feasible [] square brackets notation usage, but document. getElementById () is the first choice in syntax, because getElementById is a standard document object attribute defined in a DOM specification. By using these two methods together, which is a standard Object attribute and which is defined by the context, it is clear in the Code:

Document. forms ["myformname"]. elements ["myinput"]. value

Forms is a standard attribute of document, while form name myformname is defined by the page. At the same time, elements and value attributes are both standard attributes defined by the specification. While myinput is defined by the page. This page is a syntax that is easy to understand (the content of the Code). It is a recommended practice, but not a strict principle.

4. Avoid eval

In Javascript, the eval () function is a method for executing arbitrary code during execution. In almost all cases, eval should not be used. If it appears on your page, it indicates that you have done better. For example, eval is usually used by programmers who do not know how to use square brackets.

In principle, Eval is edevil (Eval is the devil ). Don't use it unless you are an experienced developer and know your situation.

5. Correctly Reference Form and form elements

All html forms should have a name attribute. For XHTML documents, the name attribute is not required, but the Form tag should have an id attribute and must be referenced using document. getElementById. Using an index like document. forms [0] to reference a form is a bad practice in almost all cases. Some browsers regard the elements named by form in the document as an available form attribute. This is not reliable and should not be used.

The following example uses square brackets and the correct object reference method to demonstrate how to prevent incorrect reference to the input of a form:

Correct reference form Input:

Document. forms ["formname"]. elements ["inputname"]

Bad practice:

Document. formname. inputname

If you want to reference two form elements in a function, it is better to reference this form object first and store it in the variable. This avoids repeated queries to solve the reference of the form:

The Code is as follows:


Var formElements = document. forms ["mainForm"]. elements;
FormElements ["input1"]. value = "";
FormElements ["input2"]. value = "B ";

When you use onChange or other similar event processing methods, a good way is to always reference the input element itself to the function through an introduction. All input elements have a reference to a Form containing the following:

The Code is as follows:


Input type = "text" name = "address" onChange = "validate (this )"

Function validate (input_obj ){
// Reference the form containing this element
Var theform = input_obj.form;
// Now you do not need to use hard code to reference the form itself
If (theform. elements ["city"]. value = ""){
Alert ("Error ");
}
}

By referencing form elements to access form attributes, you can write a function that does not contain hard code to reference any form with a specific name on this page. This is a good practice because functions become reusable.

6. Avoid

The with declaration in Javascript inserts an object at the front end of a scope. Therefore, any reference to attributes/variables will be resolved first by the object. This is usually used as a shortcut to avoid repeated references:

Example of using:

The Code is as follows:


With (document. forms ["mainForm"]. elements ){
Input1.value = "junk ";
Input2.value = "junk ";
}

But the problem is that the programmer has no way to verify that input1 or input2 has actually been resolved as an attribute of the Form element array. It first identifies the attributes for these names. If it cannot be found, it will continue to (down) detect this scope. Finally, input1 and input2 are treated as global objects, ending with an error.

The work und is to create a reference to reduce the referenced object and use it to solve these references.

Use a reference:

The Code is as follows:


Var elements = document. forms ["mainForm"]. elements;
Elements. input1.value = "junk ";
Elements. input2.value = "junk ";

7. Use onclick in the anchor to replace javascript: Pseudo-Protocol

If you want to trigger Javascript code in the tag, select onclick instead of JavaScript: pseudo-protocol; the Javascript code running with onclick must return true or false (or an expression than evalues to true or false). [how can this sentence be translated? I understand it as follows: an expression with a priority higher than true or false]) to return the tag itself: if true is returned, the href of the anchor will be treated as a general link; if false is returned, href is ignored. This is why return false; is often included at the end of the Code processed by onclick.

Correct syntax:

A href = "javascript_required.html" go/

In this example, the doSomething () function (defined in a corner of the page) is called when it is clicked. Href will never be accessed by a Javascript-enabled browser. In a browser where you can remind Javascript that it is necessary and disabled by the user, the document javascript_required.html will be loaded. Generally, when you make sure that the user will enable Javascript support, to simplify it as much as possible, the link will only contain href = #. This practice is not encouraged. There is usually a good practice: it can provide a page to return to the local without using javascript.

Sometimes, many users want to access a link in different situations. For example, when a user wants to leave a form page, he wants to verify first to ensure that nothing is changed. In this case, your onclick will access a function that will return to ask whether the link should be followed:

Conditional link access:

The Code is as follows:


A href = "/" Home/

Function validate (){
Return prompt ("Are you sure you want to exit this page? ");
}

In this instance, the validate () function must only return true or false. The user will be allowed to access the problematic home page, or the link will not be accessed if false. This example prompts you to confirm (its behavior) to access true or false, which is entirely determined by the user clicking confirm or cancel.

The following are some examples. If you see the following code on your page, this is incorrect and needs to be modified:

What should not be done:

The Code is as follows:


A href = "javascript: doSomething ()" link/
A href = "#" link/
A href = "#" link/
A href = "#" link/

8. Use the one dollar + Number operator to convert the type to Number
In Javascript, The + operator acts as both a mathematical plus sign and a connector. This will cause problems when adding the form field values. For example, because Javascript is a weak type language, the form field values will be processed as arrays, when you put them together, + will be treated as a connector, rather than a mathematical plus sign.

Example of a problem:

Form name = "myform" action = "[url]" input type = "text" name = "val1" value = "1" input type = "text" name = "val2" value = "2"/formfunction total () {var theform = document. forms ["myform"]; var total = theform. elements ["val1"]. value + theform. elements ["val2"]. value; alert (total); // This will pop up "12", but what you want is 3 !}


To solve this problem, Javascript requires a prompt to treat these values as numbers. You can use "+" to convert an array to a number. Adding a plus sign to a variable or expression will force it to be processed as a number, which will also allow the mathematics + to be successfully applied.

Modified code:

function total() {var theform = document.forms["myform"];var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value);alert(total); // This will alert 3}

9. Avoid document. all
Document. all is introduced by Microsoft's IE and is not a standard Javascript DOM feature. Although most new browsers support it to support bad code that depends on it, many other browsers do not.

There is no reason other methods do not apply, while an old IE browser (5.0) needs to support, while document. all is used in Javascript as a compromise. You do not need to use document. all to check whether it is an IE browser, because other browsers currently generally support it.

Only document. all is the final choice:

if (document.getElementById) {var obj = document.getElementById("myId");}else if (document.all) {var obj = document.all("myId");}

Some principles for using document. all:

• Try other methods
• As the final choice
• To support IE browsers earlier than version 5.0
• Always use if (document. all) {} to check whether it is supported.
10. Do not use HTML comments in the script code block
Some browsers such as Netscape 1995 do not support or recognize script tags in the old Javascript Day (1.0. Therefore, when Javascript is released for the first time, a technology is required to make the actual code not to be displayed as text on the old browser. There is an hack that uses HTML annotations to hide the code.

Making HTML comments is not good:

script language="javascript"!--// code here//--/script

Today, no common browser ignores the script tag. Therefore, there is no need to hide the Javascript source code. In fact, it can also be considered useless for the following reasons:

• In the XHTML document, the source code will be hidden from all browsers and rendered useless (content );
•-HTML comments are not allowed. This will invalidate any decrease operation.
 11. avoid misuse of the global namespace
Generally, all variables and functions are rarely needed. Global use may cause conflicts between the Javascript source file and the code. Therefore, a good practice is to use functional encapsulation in a global namespace. There are multiple methods to complete this task, which is relatively complicated. The simplest way is to create a global object and assign the attributes and methods to this object:

Create a namespace:

var MyLib = {}; // global Object cointainerMyLib.value = 1;MyLib.increment = function() { MyLib.value++; }MyLib.show = function() { alert(MyLib.value); }MyLib.value=6;MyLib.increment();MyLib.show(); // alerts 7

The namespace can also use Closures (Closure ?) And Private Member Variables (Private variable ?) It can also be disguised in Javascript.

12. Avoid synchronous ajax calls

When using Ajax requests, you can either select asynchronous mode or synchronous mode. When the browser behavior can continue, the asynchronous mode places the request in the background for execution, and the synchronous mode waits until the request is completed.

Avoid synchronous requests. These requests disable the browser for the user until the request is returned. Once the server is busy and it takes some time to complete the request, your browser (or OS) won't be able to do anything else until the request times out.

If you think you need the synchronization mode, the biggest possibility is that you need time to rethink your design. Few (if any) Ajax requests in synchronous mode are actually required.

13. Use JSON

When you need to store the data structure into plain text, or send/retrieve the data structure through Ajax, try to use JSON instead of XML. JSON (JavaScript Object Notation) is a more concise and effective data storage format and does not depend on any language (and is a language-neutral ).

14. Use the correct script tag

Do not use the LANGUAGE attribute in the script. An appropriate method is to create the following Javascript code block:

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.