Fourteen Writing Skills of JS

web front end eight thousand one hundred and five 14 years ago (2011-04-27)

Write any programming code, different developers will have different views. But it's always good to refer to it. The following is from the Javascript Toolbox 14 Best JS Code Writing Skills

1. Always use var

In javascript, variables are either global or functional. Using the var keyword will be the key to keep variables concise and clear. When declaring a global or function level variable, the var keyword should always be preceded. The following example will highlight the potential problem of not doing so.

Problems caused by not using Var

var i = zero ; // This is good - creates a global variable
function test() {
for (i = zero ; i   ten ; 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 refers to the global variable. It is a lot of practice to always use var to declare global variables, but the most important thing is to use var to define variables within a function range. The following two methods are functionally identical:

Correct function

function test() {
var i = zero ;
for (i = zero ; i ten ; i ++ ) {
alert(
" Hello World! " );
}
}

Correct function

function test() {
for ( var i = zero ; i ten ; i ++ ) {
alert(
" Hello World! " );
}
}

2. Characteristic test instead of browser testing

Some codes are written to discover the browser version and perform different behaviors based on the client that the user is using. This, in general, 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 detect whether it has this function or feature, and then use it. It is better to check the browser version separately, even if you know its performance. You can find an article here to discuss this issue 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 bracket notation

When access is determined by execution time or include is not available The object attribute accessed by number, using square brackets notation. If you are not an experienced Javascript programmer, it is a good idea to always use square brackets.

Object properties are accessed by two fixed methods: Notation and [] square bracket notation:

. Numbering

MyObject.property

[] Square bracket notation

MyObject[ " property " ]

Use No. and attribute name are hard codes and cannot be changed during execution. Using [] square brackets, the property name is a string obtained by calculating the property name. The string should be hard code, or a variable, or even a function that calls back the value of a letter string. If an attribute name is generated during execution, square brackets are required. If you have value1 ″, value2″, And value3 ″, and want to use the variable i=2 to access

This can run:

MyObject[ " value " + i]

This cannot:

MyObject.value + i

And in some The server In the end environment (PHP, Struts, etc.), the Form form is attached with a [] sign to indicate that the Form form must be treated as an array on the server side. So, use [] is the syntax for referencing a Javascript array. Therefore, the notation of [] is necessary:

This can run:

formref.elements[ " name[] " ]

This cannot:

formref.elements.name[]

The [] square bracket notation is recommended to always use it when it is needed (obviously). It is a personal preference and habit when it is not strictly needed. A good rule of thumb is to use Sign notation is used to access standard object properties, and [] square bracket notation is used to access object properties defined by the page. So, document["getElementById"]() It is a perfect and feasible [] square bracket notation, but document.getElementById() Syntax is preferred, because getElementById is a standard document object property defined in a DOM specification. The mixed use of these two notations makes it clear in the code which is a standard object attribute and which attribute name is defined by the context:

document.forms[ " myformname " ].elements[ " myinput " ].value

here, forms yes document A standard attribute of the table, while the table name myformname Is defined by the page. At the same time, elements and value Attributes are standard attributes defined by specifications. and myinput Is defined by the page. The syntax of this page is very easy to understand (the content of the code). It 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 on your page, it indicates that you have a better way to do it. For example, eval is often used by programmers who do not know to use square bracket notation.

In principle, Eval is evil. Don't use it unless you are an experienced developer and know that your situation is an exception.

5. Correctly reference forms 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 a corresponding id attribute, and must use document.getElementById() To reference. Using index methods like document. forms [0] to reference forms is a bad practice in almost all cases. Some browsers regard the element named by form in the document as an available form attribute. This is not reliable and should not be used.

The following example shows how to prevent the input of a form from being referenced incorrectly by using square brackets and correct object reference methods:

Correctly reference the 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 first reference the form object and store it in a variable. This avoids repeated 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 use a reference to refer the input element itself to the function. All input elements have a reference to the form including them:

input type = " text " name = " address " onChange = " validate(this) "

function validate(input_obj) {
// Reference the form containing this element
var theform = input_obj.form;
// Now you don't need to use hard code to reference the form itself
if (theform.elements[ " city " ].value == "" ) {
alert(
" Error " );
}
}

Access form attributes by referencing form elements. You can write a function without 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 in the front of a scope, so any property/variable reference will be resolved first depending on the object. This is often used as a shortcut to avoid repeated references:

Example of using with:

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 treated as an attribute of the Form element array. It first detects attributes for these names. If it cannot find them, it will continue to (downward) detect the scope. Finally, it tries to treat input1 and input2 as a global object in the global object, and this ends with an error.

An alternative is to create a reference to reduce the referenced objects 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 instead of javascript in the anchor: Pseudo-Protocol

If you want to a Javascript code is triggered in the tag. Select onclick instead of JavaScript: pseudo-protocol; Javascript code running with onclick must return true or false (or an expression than evaluations to true or false? This is my understanding: an expression with 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 will be ignored. This is why return false; Often included at the end of the code that onclick processes.

Correct syntax:

a href = " javascript_required.html " go / a

In this example, the doSomething () function (defined in a corner of the page) will be called when clicked. Href will never be accessed by Javascript enabled browsers. The document javascript_required.html will only be loaded in the browser where you can remind that Javascript is required but the user has not enabled it. Usually, when you make sure that the user will turn on Javascript support, the link will only contain href=# in order to make it as simple as possible. This practice is not encouraged. It is usually a good practice to provide a local return page without enabling javascript.

Sometimes, many want to visit a link according to the situation. For example, when a user wants to leave one of your form pages and wants to verify first to ensure that nothing has changed. In this case, your onclick will access a function that asks whether the link should be followed:

Conditional link access:

a href = " / " 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 question home page when it is true, or the link will not be accessed when it is false. This example prompts confirmation (its behavior) to access true or false, which is completely determined by the user clicking "Yes" or "Cancel".

Here are some examples of what should not be. If you see the following code in your own page, it is incorrect and needs to be modified:

What should not be done:

a href = " javascript:doSomething() " link / a
a href = " # " link / a
a href = " # " link / a
a href = " # " link / a

8. Use the unary+sign operator to turn the type to Number

In Javascript, the+operator acts as both a mathematical plus sign and a connector. This will cause problems when adding form field values. For example, because Javascript is a weakly typed language, form field values will be treated as arrays. When you+them together,+will be treated as a connector instead of a mathematical plus sign.

Examples of problems:

form name = " myform " action = " [url] "
input type = " text " name = " val1 " value = " one "
input type = " text " name = " val2 " value = " two "
/ 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 you want 3!
}

To solve this problem, Javascript needs a prompt to let it treat these values as numbers. You can use the+sign to convert an array to a number. Preceding a variable or expression with a+sign will force it to be treated as a number, which will also enable the successful application of mathematical+.

Modified code:

 

 

9. Avoid document.all

The 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, many browsers do not.

There is no reason why other methods are not applicable, and an old IE browser (5.0) needs to support it, while using document.all in Javascript as a compromise method. You don't need to use document.all to check whether it is an IE browser, because other browsers generally support it now.

Only take 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:

  • Same as trying other methods
  • When it is the last choice
  • When it is necessary to support IE browsers below 5.0
  • Always use if (document. all) {} to check whether it is supported

10. Don't script Use HTML comments in code blocks

In the old days of Javascript (1995), some browsers such as Netscape 1.0 did not support or recognize script label. Therefore, when Javascript is released for the first time, a technology is needed to prevent actual code from being displayed as text on older browsers. One hack uses HTML comments in the code to hide the code.

Makes HTML comments bad:

script language = " javascript "
!--
// code here
//
--
/ script

Today, no common browser will ignore it script label. Therefore, it is no longer necessary to hide the Javascript source code. In fact, it can also be considered useless for the following reasons:

  • In XHTML documents, the source code will be hidden from all browsers and rendered useless (content);
  • – HTML comments are not allowed. This will invalidate any decrement operation.

11. Avoid misusing the global namespace

Generally, all variables and functions are rarely required. Global use may cause Javascript source file document conflicts and code aborts. Therefore, it is a good practice to adopt functional encapsulation in a global namespace. There are multiple methods to complete this task, which is relatively complex. The simplest way is to create a global object and assign properties and methods to this object:

Create a namespace:

var MyLib = {}; // global Object cointainer
MyLib.value = one ;
MyLib.increment
= function () { MyLib.value ++ ; }
MyLib.show
= function () { alert(MyLib.value); }

MyLib.value
= six ;
MyLib.increment();
MyLib.show();
// alerts 7

Namespaces can also be created using Closures, and Private Member Variables can also be disguised in Javascript.

12. Avoid synchronous ajax calls

When using Ajax requests, you can choose either asynchronous mode or synchronous mode. When the browser behavior can continue to execute, the asynchronous mode places the request in the background for execution, and the synchronous mode will wait for the request to complete before continuing.

Requests made by synchronous mode should be avoided. These requests will disable the browser for the user until the request returns. Once the server is busy and needs some 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 needs synchronous mode, the most likely thing is that you need time to rethink your design. Few, if any, Ajax requests actually require synchronous mode.

13. Using JSON

When you need to store the data structure as 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 rely on any language.

14. Use the correct script tag

Do not cause script Use the LANGUAGE attribute in. A suitable way is to create the following Javascript code blocks:

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

 

function total() {
var theform = document.forms[ " myform " ];
var total = ( + theform.elements[ " val1 " ].value) + ( + theform.elements[ " val2 " ].value);
alert(total);
// This will alert 3
}