Seven Notes for beginners of JavaScript

Source: Internet
Author: User

Each language has a special place. For JavaScript, using VaR can declare any type of variables. This script language looks very simple, however, to write elegant code, you need to constantly accumulate experience. This article lists seven details that JavaScript Beginners should pay attention.

(1) simplified code

 

It is very simple to define objects and arrays in Javascript. We want to create an object, which is generally written as follows:

var car = new Object();car.colour = 'red';car.wheels = 4;car.hubcaps = 'spinning';car.age = 4;

The following statement can achieve the same effect:


var car = {colour:'red',wheels:4,  hubcaps:'spinning',  age:4}

The subsequent statement is much shorter, and you do not need to repeat the object name.

In addition, there is a simple way to write arrays. In the past, we declared arrays as follows:


var moviesThatNeedBetterWriters = new Array(  'Transformers','Transformers2','Avatar','Indiana Jones 4');

A more concise statement is as follows:


var moviesThatNeedBetterWriters = [  'Transformers','Transformers2','Avatar','Indiana Jones 4'];

For arrays, there is also a special thing like associating arrays. You will find that many codes define objects as follows:


var car = new Array();car['colour'] = 'red';car['wheels'] = 4;car['hubcaps'] = 'spinning';car['age'] = 4;

This is crazy. Don't be confused. "Join array" is just an alias of an object.

Another way to simplify the code is to use the ternary operator. For example:


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

We can replace this statement with the following code:


var direction = x < 200 ? 1 : -1;

 

 

(2) Use JSON as the data format

 

 

The great Douglas crockford invented the JSON data format to store data. You can use the native JavaScript method to store complex data without any extra conversion. For example:

var band = {  "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, or even as a format returned by the API, which is applied in many APIs, for example:

 

<div id="delicious"></div><script>function delicious(o){  var out = '<ul>';  for(var i=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>

Call delicious's Web service to obtain the latest bookmarks, return them in JSON format, and display them as Unordered Lists.

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

(3) Try to use JavaScript native functions

 

To find the maximum number in a group of numbers, we may write a loop, for example:

 

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

In fact, the same function can be implemented without loops:


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

The simplest method is:


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

You can even use math. Max to check the attributes supported by the browser:


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

If you want to add a class style to an element, the original method may be as follows:


function addclass(elm,newclass){  var c = elm.className;  elm.className = (c === '') ? newclass : c+' '+newclass;

The more elegant method is:


function addclass(elm,newclass){  var classes = 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 click event to a link in the list. The general practice is to write a loop and bind events to each link object. The HTML code is as follows:


The script is as follows:


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

A more reasonable statement is to bind only events to the parent object of the list. The Code is as follows:


(function(){  var resources = 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 Functions


 

One of the biggest headaches about Javascript is that its variables do not have a specific scope. Generally, all variables, functions, arrays, or objects are global, which means other scripts on the same page can access and overwrite them. The solution is to encapsulate variables in an anonymous function. For example, the following definition generates three global variables and two global functions:


var name = 'Chris';var age = '34';var status = 'single';function createMember(){  // [...]}function getMemberDetails(){  // [...]}

The package is as follows:


var myApplication = function(){  var name = 'Chris';  var age = '34';  var status = 'single';  return{    createMember:function(){      // [...]    },    getMemberDetails:function(){      // [...]    }  }}();// myApplication.createMember() and// myApplication.getMemberDetails() now works.

This is called the standalone mode and is a javascript design mode. This mode is widely used in Yui. The improved syntax is as follows:


var myApplication = function(){  var name = 'Chris';  var age = '34';  var status = 'single';  function createMember(){    // [...]  }  function getMemberDetails(){    // [...]  }  return{    create:createMember,    get:getMemberDetails  }}();//myApplication.get() and myApplication.create() now work.

(6) Configurable code


You can configure the Code to make it easier for others to use or modify. The solution is to add a configuration object to the script you write. Key points are as follows:
 
1. Add an object named configuration in your script.

2. store all the things that others may want to change in the configuration object, such as css id, class name, and language.

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

 

 

(7) Code compatibility

Compatibility is easy for beginners to ignore. When learning JavaScript
Testing in a fixed browser, and this browser is likely to be Ie, which is very fatal, because IE currently has the worst standard support among several mainstream browsers. Result displayed by the end user
Maybe the code you write cannot run correctly in a browser. You should test your code in mainstream browsers. This may be time-consuming, but it should be done.


(Source: Dream sky Source: seven JavaScript things I wish I knew much earlier in my career)

Http://www.cnblogs.com/lhb25/archive/2011/01/10/1932284.html

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.