Your location:Tech News>News>Script>15 JavaScript Best Practice Summary

Latest News

15 JavaScript Best Practice Summary

Author:fsadmin

Views:

  This document finishing most recognized and controversial JavaScript or less good writing specifications (Best Practice).Some obvious common sense is no longer discussed (such as use object supports recognition judgment, rather than the browser identification judge; for example, do not nested too deeply).Entries in order of importance in descending coarse grade.

  The external JavaScript file at the bottom of HTML

  Our goal is the same: to provide users display the contents as quickly as possible.When loading a script file time, HTML will stop parsing until the script is finished loading.Thus, the user may for a long time in front of a blank screen, looks nothing happened.If your JavaScript code just adds some features (such as a button click action), then despite the bold at the bottom of the HTML file references it (inBefore), you will see a significant speed boost.If the script file is used for other purposes, you need to carefully consider.But anyway, this is no doubt a very worthy of consideration place.

  Optimization cycle

  Loop through an array

  Copy the code code is as follows:

  // This code will have a bad time to calculate the length of the array at each entry to the loop

  var names = [ ''George'', ''Ringo'', ''Paul'', ''John''];

  for (var i = 0; i

  doSomeThingWith (names [i]);

  }

  Copy the code code is as follows:

  // this is the case, it will only be counted once the

  var names = [ ''George'', ''Ringo'', ''Paul'', ''John''];

  var all = names.length;

  for (var i = 0; i

  doSomeThingWith (names [i]);

  }

  Copy the code code is as follows:

  // This is more a brief

  var names = [ ''George'', ''Ringo'', ''Paul'', ''John''];

  for (var i = 0, j = names.length; i

  doSomeThingWith (names [i]);

  }

  Copy the code code is as follows:

  // This code is worse is that it declare a variable in the body of the loop, each loop will create variable

  for (var i = 0; i < someArray.length; i++) {

  var container = document.getElementById ( ''container'');

  container.innerHtml + = ''my number:'' + i;

  console.log (i);

  }

  Copy the code code is as follows:

  // declare variables in vitro cycle, will create a variable

  var container = document.getElementById ( ''container'');

  for (var i = 0, len = someArray.length; i < len; i++) {

  container.innerHtml + = ''my number:'' + i;

  console.log (i);

  }

  Try to use a short code

  If you can increase readability, then use the code short format makes sense, here is a non-exhaustive list:

  Copy the code code is as follows:

  // for conditional only twice, which is a lengthy wording

  var direction;

  if (x> 100) {

  direction = 1;

  } Else {

  direction = -1;

  }

  Copy the code code is as follows:

  // better code

  var direction = (x> 100) ? 1: 1;

  Copy the code code is as follows:

  // determines whether a variable is defined, and if not, to a given value, the bad code

  if (v) {

  var x = v;

  } Else {

  var x = 10;

  }

  Copy the code code is as follows:

  // better code

  var x = v || 10;

  Copy the code code is as follows:

  // repeat the variable name many times

  var cow = new Object ();

  cow.colour = ''brown'';

  cow.commonQuestion = ''What now?'';

  cow.moo = function () {

  console.log ( ''moo'');

  }

  cow.feet = 4;

  cow.accordingToLarson = ''will take over the world'';

  Copy the code code is as follows:

  // better wording is so

  var cow = {

  colour: ''brown'',

  commonQuestion: ''What now?''

  moo: function () {

  console.log ( ''moo);

  },

  feet: 4,

  accordingToLarson: ''will take over the world''

  };

  Copy the code code is as follows:

  // repeated many times group name

  var aweSomeBands = new Array ();

  aweSomeBands [0] = ''Bad Religion'';

  aweSomeBands [1] = ''Dropkick Murphys'';

  aweSomeBands [2] = ''Flogging Molly'';

  aweSomeBands [3] = ''Red Hot Chili Peppers'';

  aweSomeBands [4] = ''Pornophonique'';

  Copy the code code is as follows:

  // better code

  var aweSomeBands = [

  ''Bad Religion'',

  ''Dropkick Murphys'',

  ''Flogging Molly'',

  ''Red Hot Chili Peppers'',

  ''Pornophonique''

  ];

  Single and double quotes

  To avoid confusion, we recommend the use of double quotes in HTML, use single quotes in JavaScript.

  Copy the code code is as follows:

  // html

  

  Copy the code code is as follows:

  // JavaScript

  

  Copy the code code is as follows:

  // mix some jQuery code

  $ ( ''H1'').after ( ''

table of Contents

    '');

      Avoid mixed with other technologies

      CSS: Suppose there must fill in the input box on our pages (have class "mandatory"), if it is not the input data, it will add a red border around.

      Copy the code code is as follows:

      // some other mixed code technology to do so:

      var f = document.getElementById ( ''mainform'');

      var inputs = f.getElementsByTagName ( ''input'');

      for (var i = 0, j = inputs.length; i

      if (inputs [i].className === ''mandatory'' &&

      inputs [i].value === '''') {

      inputs [i].style.borderColor = ''# f00'';

      inputs [i].style.borderStyle = ''solid'';

      inputs [i].style.borderWidth = ''1px'';

      }

      }

      Copy the code code is as follows:

      // some code that will do good: stylized things to CSS it

      var f = document.getElementById ( ''mainform'');

      var inputs = f.getElementsByTagName ( ''input'');

      for (var i = 0, j = inputs.length;i

      if (inputs [i].className === ''mandatory'' &&

      inputs [i].value === '''') {

      inputs [i].className + = ''error'';

      }

      }

      HTML: Suppose we have a multi-HTML content within JavaScript needed to load, then the use of Ajax loading a separate file, rather than deal with JavaScript DOM, which makes the code difficult to handle and difficult to maintain compatibility issues.

      JavaScript code verification

      Browser handles JavaScript code can be very forgiving, but I suggest that you do not rely on the browser''s analytical ability, and therefore become lazy coding practices.

      The simplest test your code quality is through an online validation tool JavaScript JSLint.

      "JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems."

      - JSLint Documentation

      Using a simpler format for writing innerscript

      Copy the code code is as follows:

      // early code might look like this

      

      Copy the code code is as follows:

      // Now do not attribute the language

      

      Always check data

      To check all the data you input methods, one is for security, on the other hand also to availability.Users will input the wrong data anytime, anywhere.This is not because they are stupid, but because they are busy, and think of different ways with you.By typeof method to detect your function to accept input legality.

      Copy the code code is as follows:

      // If the type is not an array members, then the following code will throw an error

      function buildMemberList (members) {

      var all = members.length;

      var ul = document.createElement ( ''ul'');

      for (var i = 0; i

      Copy the code code is as follows:

      // good practice is to check whether the parameter is an array

      function buildMemberList (members) {

      typeof // array is the object, so if you want to determine whether the array, you can only test if it has an array of function: slice

      if (typeof members === ''object'' &&

      typeof members.slice === ''function'') {

      var all = members.length;

      var ul = document.createElement ( ''ul'');

      for (var i = 0; i

      Another threat data is taken directly from the DOM using.For example, your function to obtain a user name from the user name input box to do an operation, but the user name in single or double quotes may cause your code to crash.

      Avoid global variables

      Global variables and functions are very bad.JavaScript because all contained in a page are run in the same domain.So if your code declares global variables or global function, then the code behind the loaded script file of the same name variables and functions will overwrite (overwrite) your.

      Copy the code code is as follows:

      // bad global variables and functions

      var current = null;

      function init () {.}

      function change () {.}

      function verify () {.}

      There are many solutions, Christian Heilmann recommended approach is:

      Copy the code code is as follows:

      // if the variables and functions do not need "outside" reference, then you can use a no-name will wrap them all.

      (Function () {

      var current = null;

      function init () {.}

      function change () {.}

      function verify () {.}

      }) ();

      Copy the code code is as follows:

      // if the variables and functions required in the "outside" references need to put your variables and functions in a "name space"

      // we do here namespace with a function rather than a var, because the declaration function is simpler, but also to protect the privacy of the data in the former

      myNameSpace = function () {

      var current = null;

      function init () {.}

      function change () {.}

      function verify () {.}

      // All you need to call outside the namespace functions and properties which have to write in return

      return {

      init: init,

      // You can even name an alias for the functions and properties

      set: change

      }

      } ();

      Declare variables, always use var

      JavaScript variables in the local area may be full or partial domain, with the var statement, then will be more intuitive.

      Copy the code code is as follows:

      // confusing problem in not in function due 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!

      Copy the code code is as follows:

      // The solution is to declare variables in function with var

      function test () {

      for (var i = 0; i<10; i++) {

      alert ( "Hello World!");

      }

      }

      Used to pre-string the + into digital

      JavaScript, the "+" operator is used as a digital adding i.e., is also used to connect the string.If the request and the form of several values, it may be a problem with +.

      Copy the code code is as follows:

      // code issues will arise

      

      

      

      

      function total () {

      var theform = document.forms [ "myform"];

      var total = theform.elements [ "val1"].value + theform.elements [ "val2"].value;

      alert (total); // This will alert "12", but what you wanted was 3!

      }

      Copy the code code is as follows:

      // in string preceded by "+", which is to give a hint of JavaScript: This is a number instead of a string

      function total () {

      var theform = document.forms [ "myform"];

      var total = (+ theform.elements [ "val1"].value) + (+ theform.elements [ "val2"].value);

      alert (total); // This will alert 3

      }

      Avoid using eval () method

      In JavaScript eval () method is any code at run time as an object a method of calculating / run.In fact due to safety, in most cases you should not use eval (), there is always a more "correct" way to accomplish the same work.The basic principle is, eval is evil, do not use it at any time, unless you are a veteran, and you know you have to do this.

      for in the statement

      Through all the entries in an object when the statement is used for in handy.But sometimes we do not object traversal methods, if not, you can add a filter.

      Copy the code code is as follows:

      // add a filter for in the statement

      for (key in object) {

      if (object.hasOwnProperty (key) {

      .then do something.

      }

      }

      Do not omit lazy "and {}

      Technically, you can ignore a lot of curly braces and semicolons.

      Copy the code code is as follows:

      // Although it seems very wrong, most browsers can correctly parse the code

      if (someVariableExists)

      x = false

      Copy the code code is as follows:

      // This code looks more wrong, a quick eye and saw the following sentence appears to have been executed

      // x = false in fact only if the

      if (someVariableExists)

      x = false

      anotherFunctionCall ();

      Therefore, the principle to remember is: 1.Never omit the semicolon; 2.Do not omit the curly brackets, unless in the same row.

      Copy the code code is as follows:

      // this is OK

      if (2 + 2 === 4) return ''nicely done'';

      Get object properties when using square brackets instead of a dot

      Obtaining an object in JavaScript Properties There are two methods:

      Copy the code code is as follows:

      // Dot markers

      MyObject.property

      Copy the code code is as follows:

      // square brackets mark

      MyObject [ "property"]

      If the object is achieved with a dot mark attribute, attribute names are hard-coded and can not be changed at runtime; and square brackets, then, JavaScript will seek value within square brackets then determined by calculating the results of the property name.That is marked in square brackets embodiment, the attribute name may be hard-coded, or may be variable or function return values.

      Copy the code code is as follows:

      // this is not enough

      MyObject.value + i

      Copy the code code is as follows:

      // This is no problem

      MyObject [ "value" + i]

      Assuming that JavaScript is disabled

      I know that such an assumption would hurt the feelings of JavaScript developers, but the data in the current uncertain circumstances we should do it just to be safe assumption.This is a progressive enhancement in a very important part.

      Use JavaScript library

      There are a lot of very popular JavaScript libraries such as YUI and jQuery, Dojo.Their disadvantage is the need to download an additional file, but more advantages: more compatible; the code easier to understand.There are a lot of good library, but you should not put them in a project have to spend, because there may be compatibility issues.Choose their own habits like a.

      Do not forget the point is, no doubt native JavaScript faster, if you are using small-scale, better to use native.

      You may also be interested in: You need to know the 10 best development practices Summary javascript Javascript is best practice of object-oriented JavaScript code that skill Practice Program Practice javascript

    Recommend article

    Relate article