"Experience Summary" 14 rules to follow when writing JavaScript code _javascript tips

Source: Internet
Author: User
Tags arrays data structures eval javascript array

This article describes the 14 rules you should follow to write JavaScript code. Share to everyone for your reference, specific as follows:

1. Always use ' var '

In JavaScript, a variable is not a global scope is a function range, the use of "var" keyword is to keep the variables concise and clear key. When declaring a variable that is either global or a function level (function-level), 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 is good-creates a global variable
function test () {for
(i=0; i<10; i++) {
alert ("Hello world!") ;
}
}
Test ();
alert (i); The global variable i is 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 references a 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 range of variables for a function. 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 against 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, which detects whether a browser has this feature or feature before using an advanced feature that an old browser might not support, and then uses it. This alone detects the browser version to be better, even if you know its performance. You can find an article in http://www.jibbering.com/faq/faq_notes/not_browser_detect.html to discuss this problem in depth.

Example:

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

3. Use square brackets notation

When access is determined by execution or includes the "." The use of square brackets notation for accessing object properties. If you're not an experienced JavaScript programmer, always using square brackets is a good practice

The properties of an object are accessed by two fixed methods: "." Notation and "[]" Square bracket notation:

“.” Number notation:

Myobject.property

"[]" Square bracket notation:

Myobject["Property"]

Use the "." Number, the property name is hard code and cannot be changed at execution time. Using the brackets, the property name is a string that evaluates to a property name. The string should be hard code, or a variable, or even a function that recalls an alphabetic string value. If an attribute name is generated in execution, the square brackets are required if you have "Value1″," Value2″, and "Value3″ such attributes, and would like to use variable i=2 to access

This can be run:

myobject["value" +i]

This can not be:

Myobject.value+i

And in some server-side environments (PHP, struts, etc.), the form form is appended with a [] sign to indicate that form forms must be treated as arrays on the server side. So, with the "." Number to refer to a field containing the [] number will not be executed because [] is the syntax that references a Javascript array. Therefore, [] notation is necessary:

This can be run:

formref.elements["name[]"]

This can not be:

Formref.elements.name[]

The recommended use of the square bracket notation is to say that it is always used when it is needed (obviously). 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 "." The notation accesses the standard object properties and uses the [] bracket notation to access the object properties defined by the page. In this way, document["getElementById"] () is a perfectly viable "[]" square bracket notation usage, but document.getElementById () is preferred syntactically because getElementById is a DOM A standard Document object attribute defined in the specification. Mixing these two notation to make which is the standard object property, which attribute name is defined by the context, appears clear in the code:

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

Here, forms is a standard attribute of document, while table Single-name Myformname is defined by the page. Also, the elements and Value properties are standard attributes defined by the specification. and myinput is defined by the page. This page is a syntax that is very easy to understand (the content of the code), is a recommendation to follow the idiom, but not the 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 shows that there is a better way to do it. For example, eval is usually used by programmers who do not know how to use the square brackets notation.

In principle, "eval is evil (eval is 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 attribute. For XHTML documents, the Name property is not required, but the Form label should have the corresponding ID attribute and must be referenced with document.getElementById (). Using indexing methods such as document.forms[0 to refer to forms is a bad practice in almost all cases. Some browsers use a form as an available form attribute in the document. This is not reliable and should not be used.

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

Correct reference 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 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 the input element itself to a function through a drawing. All input elements have a reference to the form form that contains them:

<input type= "text" name= "Address" onchange= "Validate (This)" >
function Validate (input_obj) {  //reference form
var theform = Input_obj.form containing this element;  Now you may not need to use hard code to refer to the form itself
if (theform.elements["City"].value== "") {
alert ("Error");
}


By using a reference to a FORM element to access the form's properties, you can write a function that does not contain hard code to refer to any form in the page that has a specific name. This is a very good practice, because functions become reusable.

Avoid ' with '

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

Examples of using with:

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

The problem is that programmers do not have a way to verify that input1 or input2 are actually being treated as attributes of a Form element array. It first detects the attribute with these name values, and if it cannot find it, it will continue (downward) to detect the scope. Finally, it attempts 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" instead of "Javascript:pseudo-protocol" in the anchor point

If you want to trigger JavaScript code in the <a> tab, select OnClick instead of Javascript:pseudo-protocol; JavaScript code that runs with onclick must return to ture or Fals E (or a expression than evalues to True or false [how do you translate this sentence? I understand this: an expression that has a precedence greater than true or false]) to return the label itself: If True, the anchor Point's href will be treated as a generic link, or if False, the HREF will be ignored. That's why "return false;" is often included in the tail of the code that the onclick is working on.

Correct syntax:

Copy Code code as follows:
<a href= "http://www.jb51.net" onclick= "dosomething" (); return false; >go</a>

In this instance, the "dosomething ()" function (defined in a corner of the page) will be invoked when clicked. HREF will never be accessed by JavaScript-enabled browsers. Document javascript_required.html are loaded in browsers where you can alert JavaScript that they are required and that the user is not enabled. Typically, when you make sure that the user will be able to turn on Javascript support, the link will contain only href= "#" to simplify it as much as possible. This approach is not encouraged. It is usually a good idea to provide a page that is not available to enable JavaScript one to return to the local.

Sometimes, many want to be in a situation to access a link. For example, when a user wants to leave one of your form pages and want to validate to make sure nothing is changed. In this case, your onclick will access a function that asks if the link should be followed:

Conditional Link Access:

<a href= "/" onclick= "return Validate ();" >Home</a>

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

In this instance, the Validate () function must return only ture or false. Ture users will be allowed to question 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 "Yes" or "Cancel".

Here are some examples of "not supposed". If you see the following code in your own page, this is not true and needs to be modified:

What is not to be done:

<a href= "javascript:dosomething ()" >link</a> <a href= "http://www.jb51.net/#" onclick= "
DoSomething () ">link</a>
<a href=" http://www.jb51.net/# "onclick=" javascript:dosomething (); " >link</a>
<a href= "http://www.jb51.net/#" onclick= "javascript:dosomething (); return false;" >link</a>

8. Use the unary ' + ' operator to turn a type to number

In JavaScript, the "+" operator acts as both a mathematical plus and a connector. This can cause problems when the field values in form forms are added. For example, because JavaScript is a weakly typed language, the values of form fields will be treated as arrays, and when you put them "+" together, "+" will be used as a connector rather than 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 "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 "+" number to convert the array to numbers. Putting a "+" number in front of a variable or expression will force it to be treated as a number, which will make the mathematical "+" successful.

To modify a good 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 is introduced by Microsoft's IE, and is not a standard Javascript DOM feature. Although most new browsers support it to support poor code that relies on it, there are many browsers that do not support it.

There is no reason other methods do not apply, and an older IE browser (<5.0) needs support while using document.all as a compromise in JavaScript. You do not need to use document.all to detect if it is IE browser, because other browsers are now generally supported.

Only document.all as the last 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 with the same
When it is the last choice
When you need to support the 5.0 version of IE browser below
Always use ' if (document.all) {} ' to see if it is supported.

10. Do not use HTML annotations in the script code block

In the old days of Javascript (1995), some browsers, such as Netscape 1.0, do not support or recognize <script> tags. So, when Javascript is first released, there is a technique to make the actual code appear in the old browser as text. One "hack" is to use HTML annotations in your code to hide the code.

Make HTML comments not good:

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

Today, none of the commonly used browsers will ignore <script> tags. Therefore, there is no need to hide the Javascript source code again. 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 useless (content);

– The HTML annotation does not allow this to invalidate any decrement operation.

11. Avoid messing with the global namespace

In general, all variables and functions are rarely required. Global use will likely cause Javascript source file document conflicts, and code aborts. Therefore, a good practice is to use functional encapsulation in a global namespace. There are several ways to accomplish this task, which is relatively complex. The easiest way to do this is to create a global object and assign properties and methods to the object:

To create a namespace:

var mylib = {}; Global Object cointainer
mylib.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 by using Closures (closures), and private member Variables (privately variable?) can also be disguised in JavaScript.

12. Avoid synchronous ' Ajax ' calls

When using an "Ajax" request, you either select the asynchronous mode or use synchronization mode. When the browser behavior can continue, the asynchronous mode places the request in the background, and the synchronization mode waits until the request completes before continuing.

You should avoid requests that are made in sync mode. These requests will disable the browser for the user until the request is returned. Once the server is busy and requires a period of time 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 sync mode, the biggest possibility is that you need time to rethink your design. Few, if any, require AJAX requests for synchronous mode in fact.

13. Using JSON

When you need to store data structures as plain text, or send/retrieve data structures via Ajax, use JSON instead of XML whenever possible. JSON (JavaScript Object notation) is a more concise and efficient format for data storage and is not dependent on any language (and is a language-neutral).

14. Use the correct <script> label

The use of language properties in <script> is not supported. An appropriate way is to create the following Javascript code block:

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

PS: The above code has not been formatted processing, the usual format of the code will be easier to read and understand, small series here for everyone to recommend several online format and compression tools, convenient for everyone in the future development of the use of:

Online JavaScript code Landscaping, formatting tools:
Http://tools.jb51.net/code/js

JavaScript code Landscaping/compression/formatting/encryption Tools:
Http://tools.jb51.net/code/jscompress

Jsmin Online JS compression tool:
http://tools.jb51.net/code/jsmincompress

JSON code online Format/beautify/compress/edit/Convert tools:
Http://tools.jb51.net/code/jsoncodeformat

More readers interested in JavaScript-related content can view the site topics: "JavaScript switching effects and tips summary", "JavaScript Search Algorithm Skills Summary", "JavaScript animation effects and tips summary", " JavaScript error and debugging skills Summary, JavaScript data structure and algorithm skills summary, JavaScript traversal algorithm and skills summary and JavaScript mathematical calculation usage Summary

I hope this article will help you with JavaScript programming.

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.