Best JS code to write 14 tips _javascript Skills

Source: Internet
Author: User
Tags data structures javascript array

Write any programming code, different developers will have different views. But the reference is always good, the following is from the JavaScript Toolbox released 14 best JS code writing techniques.

1. Always use Var
in JavaScript, a variable is not a global scope is a function scope, using the var keyword will be the key to keep the variable simple and clear. 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 i10; i++) {
alert ("Hello world!");
}

The correct function

function test () {for
(var i=0; i10; 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 depth about this issue here.

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

Use square brackets notation when access is determined by execution or includes object properties that cannot be accessed with the. Number. If you're not an experienced JavaScript programmer, it's a good practice to always use square brackets.

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

. Number notation

Myobject.property

[] square brackets notation

Myobject["Property"]

Using the. Number, the property name is hard code and cannot be changed at execution time. Using [] square 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 attributes 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 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. Thus, using the. 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 [] square brackets 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. notation to access standard object properties and to use [] square brackets to access object properties defined by the page. Thus, document["getElementById"] () is a perfectly feasible [] 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, the 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 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:

Copy Code code as follows:

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:

Copy Code code as follows:

Input type= "text" name= "Address" onchange= "Validate"

function Validate (input_obj) {
Reference to the form containing this element
var theform = Input_obj.form;
Now you don't 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.

6 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:

Copy Code code as follows:

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 by these names, 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:

Copy Code code as follows:

var elements = document.forms["MainForm"].elements;
Elements.input1.value = "junk";
Elements.input2.value = "junk";

7. Use the onclick to replace Javascript:pseudo-protocol in the anchor point

If you want to trigger JavaScript code in a tab, select OnClick instead of Javascript:pseudo-protocol; JavaScript code that runs with onclick must return Ture or false (or Expression than Evalues to True or false [how do you translate this sentence? I understand this: an expression with precedence over true or false]) to return the label itself: If True, the anchor's href will be treated as a general , and if you return False, the HREF is ignored. That's why return false; is often included in the tail of the code that the onclick handles.

Correct syntax:

A href= "javascript_required.html" 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 turn on Javascript support, the link will contain only href=# for simplicity. 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:

Copy Code code as follows:

A href= "/" home/a

function Validate () {
return prompt ("Are you sure your 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 by the user clicking on the actual or canceling the decision.

Here are some examples that should not be. 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:

Copy Code code as follows:

A href= "javascript:dosomething ()" link/a
A href= "#" link/a
A href= "#" link/a
A href= "#" 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 be problematic when the field values of form forms are added, for example, because JavaScript is a weakly typed language, the values of form fields are treated as arrays, and when you add them together, + is treated 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. Giving a variable or an expression a plus number will force it to be treated as a number, and this will make the math + successfully applied.

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
• 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 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, no common browser ignores 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 XHTML documents, the source code is hidden from all browsers and rendered useless (content);
– is not allowed in the HTML annotation, this will 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 synchronization of Ajax calls

When using AJAX requests, you either select asynchronous mode or use synchronous 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

Does not cause the use of language properties in script. An appropriate way is to create the following Javascript code block:

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

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.