JavaScript Best Practices

Source: Internet
Author: User

Abstract: The main content of this article is the source of the third edition of JavaScript Advanced programming, because the second time after reading, according to the norms in the book, found that they did not do well in the work. So this article is also a correction of their own writing JS.

1. maintainability 1.1

understandable -other people can take over the code and understand its intentions and general approach without the full explanation of the original developer.

Intuition --the things in the code can be understood at a glance, no matter how complex the process.

adaptable -The code is written in a way that changes in data do not require a full rewrite.

Extensibility --The code architecture has been taken into account to allow for the expansion of core functionality in the future.

Debug -When something goes wrong, the code can give you enough information to determine the problem as directly as possible.

1.2 Code Conventions:

Variable and function naming

The general rules for naming are as follows:

The variable name should be a noun such as car or person.

The function name should start with a verb, such as getName (). A function that returns a Boolean type value is usually preceded by an IS, such as isenable ().

Variables and functions should use logical names and don't worry about length. Length issues can be mitigated by post-processing and compression.

Variable type transparency:

Initialize to specify the type of the variable var found=false; boolean Var-count=-1;  Digital var name= ';   string var array=[];  Array

  

1.3 Loose coupling:

1.3.1, decoupling Html/javascript

This means that some events are not executed in the HTML element with the onclick and so on, but instead HTML and JavaScript are separated, and the JavaScript is included through external files and using the DOM append behavior.

1.3.2, decoupling Css/javascript

That is, try to control the style by the class name, instead of writing the style in JS. This way if a large number of JS to change the style, maintenance will be a nightmare.

For example:

// bad element.style.color= "Red"; // goodelement.classname= "edit";

1.3.3, decoupling application logic/event handlers

This means separating the application logic from the event handler, so that the two handle each of their own things. As follows:

// Badfunctionhandlekeypress (Event) {event=eventutil.getevent (event); if(event.keycode==13){        vartarget=Eventutil.gettarget (event); varvalue=5*parseint (Target.value); if(value>10) {document.getElementById ("Error-msg"). Style.display= "Block"; }    }}//GoodfunctionValidatevalue (value) {varvalue=5*parseint (value); if(value>10) {document.getElementById ("Error-msg"). Style.display= "Block"; }}functionhandlekeypress (Event) {event=eventutil.getevent (event); if(event.keycode==13){        vartarget=Eventutil.gettarget (event); Validatevalue (Target.value)}}

1.4 Programming practices

1.4.1 Avoid global variables:

// bad  Two global variables, avoid var name= "Nicholas"function  sayname () {     //  Good    A global variable, it is recommended that var myapplication={     name:"Nicholas",     Sayname:function() {         alert (this. Name);     }}

Or

// if the variables and functions do not need to be referenced "outside", a self-executing function can be written (function() {  var name = ' Nicholas ';   function Sayname () {      alert (name);  }}) ();

1.4.2 Avoid comparison with null

      function Sortarray (values) {if (values! = null) {          Values.sort (comparator);     }} //  function  Sortarray (values) {    ifinstanceof  Array) {        values.sort (comparator);     }}

 

2. Performance

2.1 Note scope, using global lookups is much more expensive than partial lookup
The bad//contains three references to a global document object. If many times, affect performance function UpdateUI () {var imgs=document.getelementsbytagname (' img '); for (Var i=0,len=imgs.length;i<len; i++) {imgs[i].title=document.title+ "image" +i;} var Msg=document.getelementbyid (' msg '); mgs.innerhtml= "Update complete.";} good//the Document object in the local doc, and then replaces the original document in the rest of the code, it only takes one global lookup function UpdateUI () {var doc=document;var imgs= Doc.getelementsbytagname (' img '); for (Var i=0,len=imgs.length;i<len;i++) {imgs[i].title=doc.title+ "image" +i;} var Msg=doc.getelementbyid (' msg '); mgs.innerhtml= "Update complete.";}

2.2 Choose the correct method:

2.2.1. Avoid unnecessary property lookups

The complexity of the computer algorithm uses O to denote, the simplest and quickest is O (1). See

Using variables and arrays is more efficient than accessing properties on an object, which is an O (1) operation, and the latter is an O (n) operation.

Because any property lookup on an object takes longer to access a variable or array, it must be searched in the prototype chain for properties that have that name. In short, the more attribute lookups, the longer the execution time.

For example:

// Fast var value = 5; var sum = ten + value;alert (sum); // Fast var values = [5, ten]; var sum = values[0] + values[1];alert (sum); // more slowly var values = {first:5, second:10}; var sum = Values.first + values.second;alert (sum);

2.2.2 Switch statement faster

If you have a complex set of if-else statements, you can get faster code by converting to a single switch statement. You can also further refine the switch statement by organizing case statements in the most probable to most improbable order

2.2.3 Minimum number of statements

There's a place where many developers can easily create many statements, which are declarations of multiple variables. It is easy to see that the code is made up of multiple
VAR statement to declare multiple variables

In JavaScript, however, all of the
Variables can be declared using a single VAR statement.

But the individual prefers the first one.

//4 Statements--a waste ofvarCount = 5;varcolor = "Blue";varValues = [A.];varnow =NewDate ();//a statementvarCount = 5, Color= "Blue", Values= [A],now=NewDate ();//but in order to better maintain, or the first one is better. And it's not so easy to make mistakes. //so support the first form of the notation

Using arrays and object literals

// Bad//creating and initializing arrays with 4 statements-wastevarValues =NewArray (); values[0] = 123; values[1] = 456; values[2] = 789;//Creating and initializing objects with 4 statements-wastevarperson =NewObject ();p erson.name= "Nicholas";p erson.age= 29;p Erson.sayname=function() {alert ( This. name);};//Good//Create and initialize an array with just one statementvarvalues = [123, 456, 789];//Create and initialize objects with only one statementvarperson ={name:"Nicholas", Age:29, Sayname:function() {alert ( This. Name); }};

2.2.4 declaring variables outside of a for statement

// Bad//each iteration needs to check the length of the array, and each time it traverses the DOM tree to find the container element-inefficient for(vari = 0; i < somearray.length; i++) {    varcontainer = document.getElementById (' container ')); Container.innerhtml+ = ' Number: ' +i; Console.log (i);}//Goodvarcontainer = document.getElementById (' container ')); for(vari = 0, len = somearray.length; i < Len; i++) {container.innerhtml+ = ' Number: ' +i; Console.log (i);}

2.2.5 the quickest way to build a string

// This method is faster than using for var arr = [' Item 1 ', ' Item 2 ', ' Item 3 ', ...]; var list = ' <ul><li> ' + arr.join (' </li><li> ') + ' </li></ul> ';

2.3 Compression

2.3.1 File compression

Principle:

Remove additional whitespace (including line breaks);
Delete all comments;
Shorten the variable name.

JavaScript has a lot of compression tools available among the finest (controversial) is YUI compressor http://yuilibrary.com/

Tools to detect errors in JS code: JSLint www.jslint.com

Summary down, found that they do not normally abide by these norms, and slowly correct

                                                                                               

If you think the article is useful, you can also give a small red packet to encourage encouragement, haha

JavaScript Best Practices

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.