7 features to be aware of when using JavaScript

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. Simplify Your code

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

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

The following wording can achieve the same effect:

var car = {    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:

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

The more concise notation is:

var moviesthatneedbetterwriters = [  ' 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:

var car = new Array (); 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:

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

We can replace this notation with the following code:

var direction = 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:

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, even as a format returned by the API, to be applied in many APIs, such as:

<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& gt; ';  }  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:

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 functionality can be achieved without loops:

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

And the simplest of these are:

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

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

var scrolltop= 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:

function AddClass (elm,newclass) {  var c = elm.classname;  Elm.classname = (c = = = ")? Newclass:c+ ' +newclass;

And the more elegant notation 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 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:

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 is clicked    Alert (x);    E.preventdefault ();  };}) ();

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

(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 (' Ev ENT delegation: ' + x ';      E.preventdefault ();    }  };}) ();
5. Anonymous functions

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:

var name = ' Chris '; var age = ' Createmember '; var status = ' single '; function () {  //[...]} function Getmemberdetails () {  //[...]}

The following are encapsulated:

var myapplication = function () {  var name = ' Chris ';  var age = ' $ ';  var status = ' 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:

var myapplication = function () {  var name = ' Chris ';  var age = ' $ ';  var status = ' single ';  function Createmember () {    //[...]  }  function Getmemberdetails () {    //[...]  }  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 named configuration to your script.
    2. Store all the things other people might want to change in the configuration object, such as the CSS ID, class name, language, and so on.
    3. Returns this object as a public property so that others can override 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.

7 features to be aware of when using JavaScript

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.