14 best JS Code Writing Skills

Source: Internet
Author: User

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() {  for (var i=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 can.

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

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 the Javascript source 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>

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.