JavaScript Best Practices

Source: Internet
Author: User
Tags html comment

This document is a list of best practices and preferred scenarios for developing JavaScript code based on the views and experiences of many developers in the JavaScript community. Because this is a recommended table rather than a principled solution, experienced developers may have slightly different insights into the following expressions.

1. Always use ' var '

In JavaScript, variables that are not globally scoped are function-scoped, and using the "var" keyword will be the key to keeping the variables simple and clear. When declaring a variable that is either global or function-level (function-level), it is necessary to always forward the "var" keyword, the following example will emphasize the potential problem of not doing so.

Problems caused by not using Var

var i=0; This was good-creates a global variablefunction test () {for   (i=0; i<10; i++) {      alert ("Hello world!");   }} Test (); alert (i); The global variable I am now 10!

Because the variable i in the variable function does not use VAR to make it a function-level variable, in this case it refers to 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 a function-scoped variable. The following two methods are functionally identical:

The correct function

function test () {   var i=0;   for (i=0; i<10; i++) {      alert ("Hello world!");}   }

The correct function

function test () {for   (var i=0; i<10; i++) {      alert ("Hello world!");}   }
2. Feature detection rather than browser detection

Some code is written to discover the browser version and perform different behaviors on it based on the client that the user is using. This, in general, is a very bad practice. A better approach is to use feature detection, before using an advanced feature that might not be supported by an old browser, to first detect whether the feature or feature is in the browser, and then use it. This alone detects the browser version better, even if you know its performance. You can find an article in http://www.jibbering.com/faq/faq_notes/not_browser_detect.html that discusses this issue in depth.

Example:

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

When access is determined by execution or includes the "." To be unavailable. The object property of the access, using square brackets notation. If you're not an experienced JavaScript programmer, it's a good practice to always use square brackets

The properties of the object are accessed by two fixed methods: "." Notation and "[]" square brackets notation:

“.” Number notation

Myobject.property

"[]" square brackets notation

Myobject["Property"]

Use the "." , the property name is hard code and cannot be changed at execution time. Using the "[]" square brackets, the property name is a string that is computed by evaluating the property name. The string is either hard code or a variable, or even a function that recalls the value of a letter string. If a property name is generated in execution, square brackets are required if you have properties such as "Value1″," Value2″, and "Value3″, and want to use the variable i=2 to access

This can be run:

myobject["value" +i]

This can not:

Myobject.value+i

And in some server-side environments (PHP, struts, etc.), the form form is appended with the [] number to indicate that the form form must be treated as an array on the server side. So, with "." Number to reference a field containing the [] number will not be executed, because [] is the syntax for referencing a JavaScript array. Therefore, the [] notation is required:

This can be run:

formref.elements["name[]"

This can not:

Formref.elements.name[]

It is recommended to use the "[]" square brackets notation when it is necessary (obviously) to always use it. When it is not strictly necessary to use it, it is a private preference and habit. A good rule of thumb is to use "." The notation accesses the standard object properties and uses the "[]" square brackets notation to access the object properties defined by the page. Thus, document["getElementById" () is a perfectly workable "[]" square bracket notation usage, but document.getElementById () is syntactically preferred because getElementById is a DOM A standard Document object property defined in the specification. Mixing these two notation to make which is a standard object property, which is defined by the context, is clearly clear in the code:

document.forms["Myformname"].elements["Myinput"].value

Here, forms is a standard attribute of document, and table sole name myformname is defined by the page. At the same time, both the elements and the value properties are standard properties defined by the specification. The myinput is defined by the page. This page is syntactically easy to understand (the content of the code), is a recommended idiom to follow, but not a strict principle.

4. Avoid ' eval '

In JavaScript, the eval () feature is a way to execute arbitrary code during the execution period. In almost all cases, eval should not be used. If it appears on your page, it means you have a better way of doing it. For example, eval is often used by programmers who do not know to use square brackets notation.

In principle, "eval is evil (eval is the Devil)". Don't use it unless you are an experienced developer and know that your situation is an exception.

5. Correctly referencing forms and form elements

All HTML forms should have a Name property. The Name property is not required for XHTML documents, but it should have an id attribute in the Form tag and must be referenced with document.getElementById (). Using an indexing method like document.forms[0] to refer to a form is a bad practice in almost all cases. Some browsers use a form to name an element in a document as an available form property. This is not reliable and should not be used.

The following example shows how to prevent the incorrect referencing of a form's input by using square brackets and the correct object reference method:

Correctly referencing the form Input:

document.forms["FormName"].elements["InputName"]

Bad Practice:

Document.formname.inputname

If you're referencing two form elements in a function, it's a good idea to refer to the Form object first and store it in a variable. This avoids repeating the query to resolve the form's references:

var formelements = document.forms["mainform"].elements;formelements["input1"].value= "a"; formelements["Input2"]. Value= "B";

When you use OnChange or other similar event handling methods, a good practice is to always refer to the INPUT element itself in a function by a lead. All input elements have a single reference to the form form that contains it:

<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 can not use hard code to refer to the form itself   if (theform.elements["City"].value== "") {      alert ("Error");}   }

By referencing a FORM element to the properties of the form, you can write a function that does not contain hard code to refer to any one of the pages that has a specific name. This is a very good practice because the function becomes reusable.

6. Avoid ' with '

The with declaration in JavaScript inserts an object at the front end of a scope, so any reference to the property/variable will be resolved by the object first. This is often used as a quick way to avoid repeating references:

Examples of using with:

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

The problem is that programmers do not have the means to verify that input1 or input2 have actually been addressed as attributes of the Form element array. It first thought of these names to detect the property, and if it was not found, it would continue to detect the scope (down). Finally, it tries to treat INPUT1 and Input2 as a global object in the global object, which ends with an error.

The workaround is to create a reference to reduce the referenced object and use it to resolve the references.

Use a reference:

var elements = document.forms["mainform"].elements;elements.input1.value = "junk"; elements.input2.value = "junk";
7. Use "onclick" in the anchor point instead of "Javascript:pseudo-protocol"

If you want to trigger JavaScript code in the <a> tag, choose onclick instead of Javascript:pseudo-protocol; the JavaScript code that runs with the onclick must return Ture or False (or an expression than evalues to True or false [how to translate this sentence? I understand this: an expression with precedence higher than true or false]) to return the label itself: if True, the href of the anchor point is treated as a generic link, and if False is returned, the href is ignored. This is why "return false;" is often included in the tail of the code that the onclick handles.

Correct syntax:

<a onclick= "dosomething (); return false; "href=" javascript_required.html>go</a>

In this instance, the "dosomething ()" function (defined in a corner of the page) is called when it is clicked. HREF will never be accessed by JavaScript-enabled browsers. Document Javascript_required.html will not be loaded until you can warn that JavaScript is required and that the user is not enabled. Usually, when you make sure that the user will turn on JavaScript support, to be as simple as possible, the link will only contain href= "#". And this is not to be encouraged. There is usually a good practice: You can provide a page that is not enabled for JavaScript to return to local.

Sometimes, many want to divide the situation to access a link. For example, when a user wants to leave one of your form pages, they want to verify that nothing is changed. In this case, your onclick will access a function that returns whether the query link should be followed:

Conditional Link Access:

<a href= "/" onclick= "return Validate ();" >home</a>function Validate () {return confirm ("Is you sure do want to exit this page?");

In this instance, the Validate () function must return only ture or false. Ture when the user will be allowed to issue the home page, or false when the link is not accessed. This example prompts for confirmation (its behavior) to access ture or false, which is entirely determined by the user clicking "true" or "Cancel".

Here are some examples of "not supposed". If you see the following code on your page, it is not correct and needs to be modified:

What is not to be done:

<a href= "javascript:dosomething ()" >link</a><a href= "#" onclick= "dosomething ()" >link</a> <a href= "#" onclick= "javascript:dosomething ();" >link</a><a href= "#" onclick= "javascript:dosomething (); return false; " >link</a>
8. Use the unary ' + ' operator to turn the type to number

In JavaScript, the "+" operator acts as both a mathematical plus and a connector. This can cause problems when the field values of the form form are added together, for example, because JavaScript is a weakly typed language, the value of the form field will be treated as an array, and when you put them "+" together, "+" will be treated as a connector, not a mathematical plus.

Example of a problem:

<form name= "MyForm" action= "[url]" ><input type= "text" name= "Val1" value= "1" ><input type= "text" Name= " Val2 "value=" 2 "></form>function 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 needs a hint to let it handle these values as numbers. You can use the "+" sign to convert the array into numbers. Placing a "+" sign on a variable or expression will force it to be treated as a number, and this will make the math "+" a successful application.

The Modified code:

function Total () {var theform = document.forms[' MyForm '];var total = (+theform.elements["Val1"].value) + (+ theform.elements["Val2"].value); alert (total); This would alert 3}
9. Avoid document.all

Document.all was introduced by Microsoft's IE, not a standard JavaScript DOM feature. Although most new browsers support it to support bad code that relies on it, there are many browsers that are not supported.

There is no reason other methods are not applicable, and an old IE browser (<5.0) needs support, while in JavaScript use document.all as a compromise method. You don't need to use document.all to detect if it's an IE browser, because other browsers now generally support it.

Just take document.all as the last option:

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

Some principles of using document.all:

    • Try another method with
    • When it is the last choice
    • When you need to support the 5.0 version of the following IE browser
    • Always use "if (document.all) {}" to see if it is supported.
10. Do not use HTML annotations in script code blocks

In JavaScript's old Days (1995), some browsers, such as Netscape 1.0, do not support or recognize <script> tags. So, when JavaScript is first released, there is a need to have a technique to make the actual code appear as text in the old browser. There is a "hack" that hides this code by using HTML annotations in your code.

Make HTML comments not good:

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

Today, no common browser ignores <script> tags. Therefore, it is no longer necessary to hide JavaScript source code. In fact, it can also be considered unhelpful for the following reasons:

    • In an XHTML document, the source code is hidden from all browsers and rendered as useless (content);
    • – The HTML comment does not allow this to invalidate any decrement operation.
11. Avoid messing around with the global namespace

In general, all variables and functions are seldom required. Global use can cause JavaScript source file document conflicts, and code aborts. Therefore, a good practice is to use a functional encapsulation within a global namespace. There are several ways to accomplish this task, which is relatively complex. The simplest approach is to create a global object and assign properties and methods to the 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

Namespaces can also be created using Closures (closure?), and private Member Variables (private variable?) can also be disguised in JavaScript.

12. Avoid synchronous ' Ajax ' calls

When using "Ajax" requests, you either choose Asynchronous mode or use synchronous mode. When the browser behavior can proceed, the asynchronous mode places the request in the background and the synchronous mode waits for the request to complete before continuing.

Requests made by synchronous mode should be avoided. These requests will disable the browser for the user until the request is returned. Once the server is busy and takes a while to complete the request, the user's browser (or OS) will not be able to do anything else until the request times out.

If you think your situation requires a synchronous mode, the biggest possibility is that you need time to rethink your design. Rarely, if any, Ajax requests that actually require synchronous mode.

13. Using JSON

Use JSON instead of XML when you need to store data structures as plain text, or send/retrieve data structures through Ajax. JSON (JavaScript Object Notation) is a more concise and efficient data storage format and is not dependent on any language (and is a language-neutral).

14. Use the correct <script> label

Do not use the Language property in <script>. An appropriate way is to create the following JavaScript code block:

<script type= "Text/javascript" >//code here</script>

JavaScript Best Practices

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.