14 best JS Code Writing Skills

Source: Internet
Author: User
Tags javascript array
 

Write any programmingCodeDifferent developers will have different opinions. But it is always a good reference. The following is the release from the Javascript toolbox.14 best JS Code Writing Skills, Sofish translation (1, 2 ).

1. Always use 'var'

In JavaScript, variables are not in the global scope or function scope. 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 prefix 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 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; I <10; I ++) {alert ("Hello world! ");}}

Correct Function

 
Function Test () {(VaRI = 0; I <10; 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 canArticle.

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 the execution or includes the object attributes that cannot be accessed with ".", square brackets are used. If you are not an experienced JavascriptProgramAlways using square brackets is a good practice

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

"." Mark

 
Myobject. Property

"[]" Square brackets

 
Myobject ["property"]

Use ".". 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. Square brackets are required if an attribute name is generated during execution. If you have attributes such as "value1", "value2", and "value3, and 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. Therefore, referencing a field containing the [] number with the "." number will not be executed, because [] refers to the syntax of A JavaScript array. Therefore, the [] Mark method is required:

This can run:

 
Formref. elements ["name []"]

This cannot be:

 
Formref. elements. name []

We recommend that you use [] square brackets 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 "." method to access standard object attributes, and use the "[]" square brackets to access the object attributes defined by the page. In this way,Document ["getelementbyid"] ()It is a perfect method of square brackets ([]),Document. getelementbyid ()It 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

Here,FormsYesDocumentIs a standard attribute, and the form nameMyformnameIs defined by the page. At the same time,ElementsAndValueAll attributes are standard attributes defined by the specification. WhileMyinputIs 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 usedDocument. 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:

VaR formelements = Document. Forms ["mainform"]. elements; formelements ["input1"]. value = "A"; 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:

 
<Input type = "text" name = "Address" onchange = "Validate (this)"> function validate (input_obj) {// reference form var theform = input_obj.form containing this element; // 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.

Avoid 'with'

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:

 
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:

 
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<A>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" onclick = "dosomething (); Return false;"> go </a>

In this instance, the "dosomething ()" function (defined in a corner of the page) will be called when 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:

 
<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 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 "OK" or "cancel.

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

What should not 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 '+' 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 "+" 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"> </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 requires a prompt to treat these values as numbers. You can use "+" to convert an array to a number. Adding a "+" sign to a variable or expression will force it to be processed as a number, which will also allow the mathematics "+" to be applied successfully.

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, and an old IE browser (<5.0) needs to support, while document. All is used as a compromise in JavaScript. 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 5.0
    • Always use "If (document. All) {}" to check whether it is supported.
10. Do not use HTML comments 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>Label. 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 a "hack" that uses HTML annotations in the code to hide the code.

Making HTML comments is not good:

 
<Script language = "JavaScript"> <! -- // Code here // --> </SCRIPT>

Today, no common browser will ignore<SCRIPT>Label. Therefore, there is no need to hide JavascriptSource code. In fact, it can also be considered useless for the following reasons:

    • In the XHTML document, the source code is 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 an "ajax" request, you must 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 cause<SCRIPT>Use the language attribute in. An appropriate method 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.