Seven JavaScript tips I should have known (1)

Source: Internet
Author: User

I have been writing JavaScript code for a long time, and I cannot remember the beginning of my time. I am very excited about the achievements of the JavaScript language in recent years. I am lucky to be one of those achievements. I have written many articles, chapters, and a book devoted to it. However, I can still find some new knowledge about this language. The following describes the past, which makes it impossible for me to say "Ah !" You should try these skills now, instead of waiting for the future to discover them by chance.

Concise writing

One of my favorite in JavaScript is the shorthand method for generating objects and arrays.

In the past, if you want to create an object, you need:

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

The following statement can achieve the same effect:

 
 
  1. var car = {  
  2. colour:'red',  
  3. wheels:4,  
  4. hubcaps:'spinning',  
  5. age:4  

It's much simpler. You don't need to use the name of this object repeatedly.

In this way, the car is defined. You may encounter invalidUserInSession, which only happens when you use IE. Remember that you don't need to write a semicolon before the right braces, so you won't be in trouble.

Another convenient shorthand is for arrays.

The traditional method for defining arrays is as follows:

 
 
  1. var moviesThatNeedBetterWriters  
  2. = new Array(  
  3. 'Transformers','Transformers2','Avatar','Indiana  
  4. Jones 4'  
  5. ); 

The short version is as follows:

 
 
  1. var moviesThatNeedBetterWriters  
  2. = [  
  3. 'Transformers','Transformers2','Avatar','Indiana  
  4. Jones 4'  
  5. ]; 

There is a problem with arrays. In fact, there is no graph group function. But you will often find someone defining the above car, just like this

 
 
  1. var car = new Array();  
  2. car['colour'] = 'red';  
  3. car['wheels'] = 4;  
  4. car['hubcaps'] = 'spinning';  
  5. car['age'] = 4; 

Arrays are not omnipotent; this write is incorrect and confusing. Graph groups are actually object functions, and people confuse these two concepts.

Another cool shorthand method is to use a Trielement conditional symbol.

You don't have to write the following...

 
 
  1. var direction;  
  2. if(x < 200){  
  3.  direction = 1;  
  4. } else {  
  5.  direction = -1;  

You can use the ternary conditional symbol to simplify it:

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

If the condition is true, the value following the question mark is used. Otherwise, the value following the colon is used.

Store data in JSON format

Before I found JSON, I used various crazy methods to store data in JavaScript's inherent data types, such as arrays, strings, there are symbols that are easy to split and other annoying things in the middle.

After Douglas Crockford invented JSON, everything changed.

Using JSON, you can use JavaScript's own functions to store data in complex formats, and you can directly access and use it without additional conversions.

JSON is the abbreviation of "JavaScript Object Notation". It uses the two abbreviated methods mentioned above.

So if you want to describe a band, you may write it like this:

 
 
  1. var band = {  
  2.  "name":"The Red Hot Chili Peppers",  
  3.  "members":[  
  4.  {  
  5.  "name":"Anthony Kiedis",  
  6. "role":"lead vocals" 
  7.  },  
  8.  {  
  9.  "name":"Michael 'Flea' Balzary",  
  10.  "role":"bass guitar, trumpet, backing vocals" 
  11.  },  
  12.  {  
  13. "name":"Chad Smith",  
  14.  "role":"drums,percussion" 
  15.  },  
  16.  {  
  17.  "name":"John Frusciante",  
  18.  "role":"Lead Guitar" 
  19.  }  
  20.  ],  
  21.  "year":"2009" 

You can directly use JSON in JavaScript, encapsulate it in a function, or even use it as the return value form of an API.

We call this JSON-P, and many APIs use this form.

You can call a data provider source to directly return JSON-P data in script code:

 
 
  1. <div id="delicious"></div><script>  
  2. function delicious(o){  
  3.  var out = '<ul>';  
  4.  for(var i=0;i<o.length;i++){  
  5.  out += '<li><a  
  6. href="' + o[i].u + '">' +  
  7.  o[i].d + '</a></li>';  
  8.  }  
  9.  out += '</ul>';  
  10.  document.getElementById('delicious').innerHTML  
  11. = out;  
  12. }  
  13. </script>  
  14. <script src="http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious"></script> 

This is to call the Web service function provided by the Delicious website to obtain the list of recent unordered bookmarks in JSON format.

Basically, JSON is the easiest way to describe complex data structures, and it can run in a browser.

You can even use the json_decode () function in PHP to run it.

Built-in functions of JavaScript (Math, Array, and String)

One thing that surprised me was that when I studied math and String functions in JavaScript, I found they greatly simplified my programming work.

With them, you can save complex loop processing and condition judgment.

For example, when I need to implement a function to find the largest number in the number array, I used to write this loop like this:

 
 
  1. var numbers =  
  2. [3,342,23,22,124];  
  3. var max = 0;  
  4. for(var i=0;i<numbers.length;i++){  
  5.  if(numbers[i]  
  6. > max){  
  7. max = numbers[i];  
  8. }  
  9. }  
  10. alert(max); 

We can achieve this without loops:

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

Note that you cannot perform sort () on an array of numeric characters, because in this case it will only be sorted alphabetically.

If you want to know more usage, read this good sort () Article.

Another interesting function is Math. max ().

This function returns the largest number in the parameter:

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

Because this function can verify the number and return the largest one, you can use it to test the browser's support for a feature:

 
 
  1. var scrollTop=Math.max(  
  2. doc.documentElement.scrollTop,  
  3. doc.body.scrollTop  
  4. ); 

This is used to solve the IE problem. You can get the scrollTop value of the current page, but according to the DOCTYPE on the page, only one of the above two attributes will store this value, and the other attribute will be undefined, so you can use Math. max () gets this number.

Read this article to learn more about how to use mathematical functions to simplify JavaScript.

In addition, a pair of very useful functions for operating strings are split () and join (). I think the most representative example is to write a function to add CSS styles to page elements.

Yes. When you attach a CSS class to a page element, either it is the first CSS class of the element, or it already has some class

, Add a space after the existing class, and then append the class. When you want to remove this class, you also need to remove the spaces in front of this class (this is very important in the past, because some old browsers do not know the class followed by spaces ).

The original writing method is as follows:

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

You can use the split () and join () functions to automatically complete this task:

 
 
  1. function addclass(elm,newclass){  
  2.  var classes =elm.className.split(' ');  
  3. classes.push(newclass);  
  4.  elm.className = classes.join(' ');  

This ensures that all classes are separated by spaces, and the class you want to append is placed at the end.

Event Delegate

Web applications are all event-driven. I like event processing, and especially I like to define events myself.

It makes your product scalable without modifying the core code.

There is a big problem (it can be said that it is a powerful performance), it is about the removal of events on the page. You can install an event listener for an element to start running.

But there is no indication on the page that there is a listener. This kind of non-performance problem (this is especially a headache for some new users), as well as "browsers like IE6" may encounter various memory problems when too many event listening requests are used, you have to admit that it is wise to use event programming as little as possible.

Therefore, event delegation emerged.

When an event is triggered on an element on the page, and in the DOM inheritance relationship, all the child elements of this element can also receive this event, in this case, you can use an event processor on the parent element to process the event, instead of using a bunch of event listeners on each child element.

What exactly does it mean? In this case, there are many hyperlinks on the page. You don't want to use these links directly and want to use a function to call this link,

The HTML code is as follows:

 
 
  1. <ul id="resources">  
  2. <li><a href="http://opera.com/wsc">Opera Web Standards  
  3. Curriculum</a></li>  
  4. <li><a href="http://sitepoint.com">Sitepoint</a></li>  
  5. <li><a href="http://alistapart.com">A List Apart</a></li>  
  6. <li><a href="http://yuiblog.com">YUI Blog</a></li>  
  7. <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>  
  8. <li><a href="http://oddlyspecific.com">Oddly specific</a></li>  
  9. </ul> 

A common practice is to loop through these links and attach an event processor to each link:

 
 
  1. // Typical event handling example
  2. (Function (){
  3. Var resources
  4. = Document. getElementById ('resources ');
  5. Var links =
  6. Resources. getElementsByTagName ('A ');
  7. Var all =
  8. Links. length;
  9. For (var I = 0; I <all; I ++ ){
  10. // Attach a listener to each link
  11. Links [I]. addEventListener ('click', handler, false );
  12. };
  13. Function handler (e ){
  14. Var x =
  15. E.tar get; // Get the link that was
  16. Clicked
  17. Alert (x );
  18. E. preventDefault ();
  19. };
  20. })();

We can also complete this task with an event processor:

 
 
  1. (function(){  
  2.  var resources= document.getElementById('resources');  
  3.  resources.addEventListener('click',handler,false);  
  4. function handler(e){  
  5.  var x =e.target; // get the link tha  
  6.  if(x.nodeName.toLowerCase()  
  7. === 'a'){  
  8.  alert('Event  
  9. delegation:' + x);  
  10.  e.preventDefault();  
  11.  }  
  12.  };  
  13. })(); 

Because click events occur in these page elements, all you need to do is compare their nodeName to find the element that should respond to this event.

Disclaimer: The two event examples mentioned above can run in all browsers. Except for IE6, you need to use an event model on IE6, it is not a simple W3C standard implementation. This is why we recommend some toolkit.

The benefit of this method is not limited to reducing multiple event processors to one. For example, you need to dynamically append more links to the chain table. After event delegation, you do not need to make other modifications. Otherwise, you need to recycle the chain table and re-install the event processor for each link.


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.