Seven details to note for JavaScript beginners

Source: Internet
Author: User

Each language has its own special place, for JavaScript, using VAR can declare any type of variable, the script language seems simple, but want to write elegant code is need to accumulate experience. This article makes a list of seven details that JavaScript beginners should pay attention to and share with you.

(1) Simplified code

JavaScript defines objects and arrays very simply, we want to create an object, which is generally written like this:

12345 varcar = newObject();car.colour = ‘red‘;car.wheels = 4;car.hubcaps = ‘spinning‘;car.age = 4;

The following wording can achieve the same effect:

123456 varcar = {    colour:‘red‘,    wheels:4,  hubcaps:‘spinning‘,  age:4}

The latter is much shorter, and you don't need to repeat the name of the object.

In addition to the array also has a concise way of writing, in the past we declared that the array is written like this:

123 varmoviesThatNeedBetterWriters = newArray(  ‘Transformers‘,‘Transformers2‘,‘Avatar‘,‘Indiana Jones 4‘);

The more concise notation is:

123 varmoviesThatNeedBetterWriters = [  ‘Transformers‘,‘Transformers2‘,‘Avatar‘,‘Indiana Jones 4‘];

For arrays, there is an associative array such a special thing. You will find a lot of code that defines objects like this:

12345 varcar = newArray();car[‘colour‘] = ‘red‘;car[‘wheels‘] = 4;car[‘hubcaps‘] = ‘spinning‘;car[‘age‘] = 4;

This is crazy, don't be confused, "associative array" is just an alias of an object.

Another way to simplify the code is to use the ternary operator, for example:

123456 vardirection;if(x < 200){  direction = 1;else{  direction = -1;}

We can replace this notation with the following code:

1 vardirection = x < 200 ? 1 : -1;

(2) using JSON as the data format

The great Douglas Crockford invented the JSON data format to store data, and you can use native JavaScript methods to store complex data without having to make any additional transformations, such as:

12345678910111213141516171819202122 varband = {  "name":"The Red Hot Chili Peppers",  "members":[    {      "name":"Anthony Kiedis",      "role":"lead vocals"    },    {      "name":"Michael ‘Flea‘ Balzary",      "role":"bass guitar, trumpet, backing vocals"    },    {      "name":"Chad Smith",      "role":"drums,percussion"    },    {      "name":"John Frusciante",      "role":"Lead Guitar"    }  ],  "year":"2009"}

You can use JSON directly in JavaScript, even as a format returned by the API, to be applied in many APIs, such as:

123456789101112 <div id="delicious"></div><script>functiondelicious(o){  varout = ‘<ul>‘;  for(vari=0;i<o.length;i++){    out += ‘<li><a href="‘+ o[i].u + ‘">‘+           o[i].d + ‘</a></li>‘;  }  out += ‘</ul>‘;  document.getElementById(‘delicious‘).innerHTML = out;}</script><script src="http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious"></script>

This calls delicious's Web service to get the latest bookmarks, return them in JSON format, and then display them in the form of unordered lists.

In essence, JSON is the most lightweight way to describe complex data, and it runs directly in the browser. You can even call the Json_decode () function in PHP to use it.

(3) use JavaScript native functions as much as possible

To find the largest number in a set of numbers, we might write a loop, for example:

12345678 varnumbers = [3,342,23,22,124];var max = 0;for(vari=0;i<numbers.length;i++){  if(numbers[i] > max){    max = numbers[i];  }}alert(max);

In fact, the same functionality can be achieved without loops:

123 varnumbers = [3,342,23,22,124];numbers.sort(function(a,b){returnb - a});alert(numbers[0]);

And the simplest of these are:

1 Math.max(12,123,3,2,433,4); // returns 433

You can even use Math.max to detect which properties the browser supports:

1234 varscrollTop= Math.max( doc.documentElement.scrollTop, doc.body.scrollTop);

If you want to add a class style to an element, the original notation might look like this:

123 functionaddclass(elm,newclass){  varc = elm.className;  elm.className = (c === ‘‘) ? newclass : c+‘ ‘+newclass;

And the more elegant notation is:

12345 functionaddclass(elm,newclass){  varclasses = elm.className.split(‘ ‘);  classes.push(newclass);  elm.className = classes.join(‘ ‘);}

(4) Event delegation

Events are a very important part of JavaScript. We want to bind a fixed-point event to a link in a list, and the general practice is to write a loop that binds events to each linked object, with the HTML code as follows:

123456789 <ul id="resources">  <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>  <li><a href="http://sitepoint.com">Sitepoint</a></li>  <li><a href="http://alistapart.com">A List Apart</a></li>  <li><a href="http://yuiblog.com">YUI Blog</a></li>  <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>  <li><a href="http://oddlyspecific.com">Oddly specific</a></li></ul>

The script is as follows:

123456789101112131415 // Classic event handling example(function(){  varresources = document.getElementById(‘resources‘);  varlinks = resources.getElementsByTagName(‘a‘);  varall = links.length;  for(vari=0;i<all;i++){    // Attach a listener to each link    links[i].addEventListener(‘click‘,handler,false);  };  functionhandler(e){    var x = e.target; // Get the link that was clicked    alert(x);    e.preventDefault();  };})();

A more logical notation is to bind events only to the parent of the list, with the following code:

1234567891011 (function(){  varresources = document.getElementById(‘resources‘);  resources.addEventListener(‘click‘,handler,false);  function handler(e){    var x = e.target; // get the link tha    if(x.nodeName.toLowerCase() === ‘a‘){      alert(‘Event delegation:‘+ x);      e.preventDefault();    }  };})();

(5) Anonymous function

One of the most frustrating things about JavaScript is that its variables do not have a specific scope. In general, any variable, function, array, or object is global, which means that other scripts on the same page can access and overwrite them. The workaround is to encapsulate the variables in an anonymous function. For example, the following definition produces three global variables and two global functions:

123456789 varname = ‘Chris‘;var age = ‘34‘;var status = ‘single‘;function createMember(){  // [...]}functiongetMemberDetails(){  // [...]}

The following are encapsulated:

123456789101112131415 varmyApplication = function(){  varname = ‘Chris‘;  varage = ‘34‘;  varstatus = ‘single‘;  return{    createMember:function(){      // [...]    },    getMemberDetails:function(){      // [...]    }  }}();// myApplication.createMember() and// myApplication.getMemberDetails() now works.

This is called the monomer mode, is a JavaScript design pattern, this mode is used very much in Yui, the improvement of the wording is:

12345678910111213141516 varmyApplication = function(){  varname = ‘Chris‘;  varage = ‘34‘;  varstatus = ‘single‘;  functioncreateMember(){    // [...]  }  functiongetMemberDetails(){    // [...]  }  return{    create:createMember,    get:getMemberDetails  }}();//myApplication.get() and myApplication.create() now work.

(6) code configurable

The code you write is configurable if you want to make it easier for others to use or modify, and the solution is to add a configuration object to the script you write. Key points are as follows:

1. Add a new object called configuration to your script.

2, in the configuration object to store all other people may want to change things, such as the CSS ID, class name, language and so on.

3. Return this object as a public property so that others can rewrite it.

(7) code compatibility

Compatibility is easy for beginners to ignore, usually learning JavaScript is in a fixed browser to test, and this browser is likely to be IE, this is very deadly, because the current few major browsers, IE is the worst of the standard support. The end user may see the result that the code you write does not work correctly in a browser. You should test your code in a mainstream browser, which may be time-consuming, but should do so.

Seven details to note for JavaScript beginners

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.