This article describes 14 rules that should be followed when writing JavaScript code. Share it for your reference, as follows:
1. Always use 'var'
In JavaScript, variables are either globally or function-wide. Using the "var" keyword will be the key to keeping the variables concise and clear. When declaring a variable that is either global or function-level, the "var" keyword must always be preceded. 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 example it references a global variable. Always using var to declare global variables is a lot of practice, but it is crucial to use var to define a function-wide variable. The following two methods are functionally the same:
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 the user is using. This, in general, is a very bad practice. A better approach is to use feature detection, first detect (the browser's) whether there is this feature or feature before using an advanced feature that an old browser may not support, and then use it. This individually detects the browser version comes better, even if you know its performance. You can find an article that discusses this issue in depth at http://www.jibbering.com/faq/faq_notes/not_browser_detect.html.
example:
if (document.getElementById) {var element = document.getElementById('MyId');} else {alert('Your browser lacks the capabilities required to run this script!');}3. Use square bracket notation
When accessing is determined by execution or includes object properties that cannot be accessed with the "." sign, square bracket notation is used. If you are not an experienced Javascript programmer, always using square brackets is a good way to do it
The properties of an object are accessed by two fixed methods: "."Noun and "[ ]" square bracket notation:
"." notation method:
MyObject.property
"[ ]" square bracket notation:
MyObject["property"]
Use the "." sign, the attribute name is hard code and cannot be changed during execution. Using the "[ ]" square brackets, the attribute name is a string that comes from calculating the attribute name. A string should be hard code, or a variable, or even a function that calls back a string value. If an attribute name is generated during 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 it
This can run:
MyObject["value"+i]
This cannot be:
MyObject.value+i
And in some server-side environments (PHP, Struts, etc.), Form forms are attached with [ ] numbers to indicate that Form forms must be treated as arrays on the server side. In this way, using the "." sign to refer to a field containing the [ ] sign will not be executed because [ ] is the syntax for referring to a Javascript array. Therefore, [ ] notation is necessary:
This can run:
formref.elements["name[]"]
This cannot be:
formref.elements.name[]
The recommended use of "[ ]" square bracket notation means that it is always used when it needs it (obviously). It is a private preference and habit when it is not strictly necessary to use it. A good empirical principle is to use the "." notation to access standard object properties and use the "[]" square bracket notation to access object properties defined by the page. In this way, document["getElementById"]() is a perfectly feasible "[ ]" square bracket notation usage, but document.getElementById() is syntactically preferred because getElementById is a standard document object property defined in a DOM specification. Mix these two notations to make which is a standard object attribute and which attribute name is defined by the context makes it clear in the code:
document.forms["myformname"].elements["myinput"].value
Here, forms is a standard property of document, and the form name myformname is defined by the page. At the same time, the elements and value attributes are both standard attributes defined by the specification. Myinput is defined by the page. This page is syntax that makes people very easy to understand (the content of the code), and is a recommended idiom, but not a strict principle.
4. Avoid 'eval'
In Javascript, the eval() function is a method to execute arbitrary code during execution. In almost all cases, eval should not be used. If it appears in your page, it means there is a better way to what you are doing. For example, eval is usually used by programmers who don't know to use square bracket 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. Correct references to 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 the corresponding id attribute and must be referenced with document.getElementById(). Using indexing methods like document.forms[0] to reference forms is a bad practice in almost all cases. Some browsers treat elements named in documents using form as an available form attribute. This is not reliable and should not be used.
The following example shows how to prevent incorrect reference of a form input using square brackets and correct object reference method:
Correct reference form Input:
document.forms["formname"].elements["inputname"]
Bad approach:
document.formname.inputname
If you want to reference two form elements in a function, it is better to refer to the form object first and store it in a variable. This avoids duplicate queries to resolve form 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 into the function through a entries. All input elements carry a reference to the Form form that contains it:
<input type="text" name="address" onChange="validate(this)">
function validate(input_obj) { // Reference formvar theform containing this element = input_obj.form; // Now you can refer to the form itself without using hard code if (theform.elements["city"].value=="") {alert("Error");}}By accessing the form's properties by referencing the form element, you can write a function that does not contain hard code to refer to any form on this page with a specific name. This is a very good practice because the functions become reusable.
Avoid 'with'
The with declaration in Javascript inserts an object on the front end of a scope, so any reference to attributes/variables will be resolved first based on the object. This is often used as a shortcut to avoid duplicate references:
Example of using with:
with (document.forms["mainForm"].elements) {input1.value = "junk";input2.value = "junk";}But the problem is that programmers do not have a way to verify that input1 or input2 has actually been solved as properties of Form elements arrays. It first detects the attribute with these name values, and if it cannot be found, it will continue to detect this scope (downward). Finally, it tries to treat input1 and input2 as a global object, and this ends with an error.
The workaround is to create an object that reduces references and use it to resolve these references.
Use a reference:
var elements = document.forms["mainForm"].elements;elements.input1.value = "junk";elements.input2.value = "junk";
7. Use "onclick" in anchor instead of "javascript: Pseudo-Protocol"
If you want to trigger Javascript code in the <a> tag, choose onclick instead of JavaScript: pseudo-protocol; Javascript code running using onclick must return ture or false (or an expression than evaluations to true or false [How to translate this sentence? I understand this way: an expression with priority above true or false]) to return the tag itself: if true, the href of the anchor will be treated as a general link; if false, the href will be ignored. That's why "return false;" is often included at the end of the code processed by onclick.
Correct syntax:
Copy the code as follows:<a href="//www.VeVB.COM" 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. The document javascript_required.html will be loaded in a browser where you can remind Javascript that is necessary and not enabled by the user. Usually, when you make sure that the user will enable Javascript support, for as much as possible, the link will only include href="#". And this approach is not encouraged. There is usually a good approach: it can provide a page that returns to the local area without using JavaScript.
Sometimes, many people want to visit a link according to situations. For example, when a user wants to leave one of your form pages and want to verify first to make sure nothing is changed. In this case, your onclick will access a function that returns a query 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 return only ture or false. When the user is in the ture, the user will be allowed to issue the home page, or when the link is not accessed. This example prompts confirmation (its behavior) to access the ture or false, which is entirely determined by the user clicking "real" or "cancel".
Here are some examples of "shouldn't be". If you see the following code in your page, this is incorrect and needs to be modified:
What shouldn't be done:
<a href="javascript:doSomething()">link</a><a href="//www.VeVB.COM/#" onClick="doSomething()">link</a><a href="//www.VeVB.COM/#" onClick="javascript:doSomething();">link</a><a href="//www.VeVB.COM/#" onClick="javascript:doSomething(); return false;">link</a>
8. Use the unary '+' operator to turn the type to Number
In Javascript, the "+" sign operator acts as both a mathematical plus sign and a connector. This can cause problems when the field values of the form form are added together. For example, because Javascript is a weak-type language, the value of the form field will be processed as an array, and when you take them together, the "+" will be treated as a connector, not a mathematical plus sign.
Examples of problems:
<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 prompt to make it process these values as numbers. You can use the "+" sign to convert an array into a number. Presenting a variable or expression with a "+" sign will force it to be processed as a number, and this will also enable the math "+" to be successfully applied.
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 was 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, (and) there are many browsers that don't support it.
There is no reason other methods are not applicable, and an old IE browser (<5.0) needs support, and document.all is used in Javascript as a tradeoff. You do not need to use document.all to detect whether it is an IE browser, because other browsers now generally support it.
Only document.all is 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
When it is the last choice
When it is required to support IE browsers below version 5.0
Always use "if (document.all) { }" to see if it is supported.
10. Do not use HTML comments in script code blocks
In the old days of Javascript (1995), some browsers such as Netscape 1.0 did not support or recognize the <script> tag. So, when Javascript was first released, there was a technology that would prevent the actual code from being displayed on older browsers as text. There is a "hack" that uses HTML comments in the code to hide these codes.
Making HTML comments not good:
<script language="javascript"><!-- // code here //--></script>
Today, no commonly used browser ignores the <script> tag. Therefore, there is no need to hide the Javascript source code anymore. In fact, it can also be considered unhelpful for the following reasons:
In XHTML documentation, the source code will be hidden from all browsers and rendered to useless (content);
The HTML comments are not allowed, this will invalidate any decrement operation.
11. Avoid using global namespaces indiscriminately
Generally, all variables and functions are rarely needed. Global use may cause Javascript source file document conflicts, and code aborts. Therefore, a good practice is to adopt functional encapsulation within a global namespace. There are multiple ways to complete this task, which is relatively complicated. The easiest way is to create a global object and assign properties and methods to this object:
Create a namespace:
var MyLib = {}; // global Object containerMyLib.value = 1;MyLib.increment = function() {MyLib.value++;}MyLib.show = function() {alert(MyLib.value);}MyLib.value=6;MyLib.increment();MyLib.show(); // alerts 7Namespaces can also be created using Closures, and Private Member Variables can also be disguised in Javascript.
12. Avoid synchronous 'ajax' calls
When using "Ajax" request, you either select asynchronous mode or use synchronous mode. When the browser behavior can continue to be executed, asynchronous mode places the request in the background and synchronous mode will wait until the request is completed before continuing.
Requests made in synchronization mode should be avoided. These requests will disable the browser to the user until the request returns. Once the server is busy and takes some time to complete the request, the user's browser (or OS) will not be able to do anything else until the request timed out.
If you feel your situation requires synchronization mode, the biggest possibility is that you need time to rethink your design. Rarely, if any, Ajax requests in synchronous mode are actually required.
13. Using JSON
When it is necessary to store the data structure into plain text, or send/retrieve the data structure through Ajax, use JSON instead of XML as much as possible. JSON (JavaScript Object Notation) is a more concise and efficient data storage format and does not rely on any language (and is a language-neutral).
14. Use the correct <script> tag
The use of the LANGUAGE property in <script> is not favored. A suitable way is to create the following Javascript code block:
<script type="text/javascript">// code here</script>
PS: The above code has not been formatted, and the formatted code will usually be easier to read and understand. Here are a few online formatting and compression tools for you to use in future development:
Online JavaScript code beautification and formatting tools:
http://tools.VeVB.COM/code/js
JavaScript code beautification/compression/formatting/encryption tools:
http://tools.VeVB.COM/code/jscompress
jsmin online js compression tool:
http://tools.VeVB.COM/code/jsmincompress
json code online formatting/beautification/compression/editing/converting tools:
http://tools.VeVB.COM/code/jsoncodeformat
For more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm skills", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm skills", "Summary of JavaScript traversal algorithms and techniques", and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.