Seven JavaScript and JavaScript skills that should have been known

Source: Internet
Author: User

Seven JavaScript and JavaScript skills that should have been known

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:

 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 }

It's much simpler. You don't need to use the name of this object repeatedly. In this way, the car is defined, and you may encounter invalidUserInSession, which only happens when you use IE. Remember that you don't need to write a comma in front of 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:

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

The short version is as follows:

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

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

 var car = new Array(); car['colour'] = 'red'; car['wheels'] = 4; car['hubcaps'] = 'spinning'; 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...

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

You can use the ternary conditional symbol to simplify it:
Var direction = 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:

 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 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:

 <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>

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. One thing that surprised me about the built-in functions of JavaScript (Math, Array, and String) is that when I studied math and String functions in JavaScript, I found that they can greatly simplify 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:

 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);

We can achieve this without loops:

 var numbers = [3,342,23,22,124]; numbers.sort(function(a,b){return b - a}); 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:
Math. max (12,123, 433, 433,4); // returns
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:

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

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 classes, 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:

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

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

 function addclass(elm,newclass){  var classes = elm.className.split(' ');  classes.push(newclass); 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 like this:

 

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

// Typical event processing 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.tar get; // Get the link that was clicked alert (x); e. preventDefault ();};})();

We can also complete this task with an event processor:

 (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();  }  }; })();

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, instead of 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.

Anonymous functions and modularity

The most annoying thing in JavaScript is that the variable has no scope of use. All variables, functions, arrays, and objects are considered global as long as they are not inside the function. That is to say, other scripts on this page can also access it, and overwrite it.

The solution is to put your variable inside an anonymous function and call it immediately after definition. For example, the following statement generates three global variables and two global functions:

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

If other scripts on this page also contain a variable named status, the problem may occur. If we encapsulate them in a myApplication, this problem will be solved:

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

However, in this way, there is no function outside the function. If this is what you need, you can. You can also save the function name:

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

If you want to use something outside the function, make some modifications. To access createMember () or getMemberDetails (), you need to convert them into attributes of myApplication to expose them to the external world:

Var myApplication = function () {var name = 'chris '; var age = '34'; var status = 'single'; return {createMember: function () {// [...]}, getMemberDetails: function () {// [...]} (); // myApplication. createMember () and // myApplication. getMemberDetails () can be used.

This is called the module mode or singleton. Douglas Crockford has talked about this many times, and Yahoo User Interface Library YUI has a lot of usage. But what makes me feel inconvenient is that I need to change the sentence pattern so that functions and variables can be accessed by the outside world. Even more, I need to add the prefix "myApplication" to the call. Therefore, I do not like this. I prefer to simply export pointers of elements that can be accessed by the outside world. This simplifies the writing of external calls:

Var myApplication = function () {var name = 'chris '; var age = '34'; var status = 'single'; function createMember () {// [...]} function getMemberDetails () {// [...]} return {create: createMember, get: getMemberDetails} (); // write it as myApplication. get () and myApplication. create.

I call this "revealing module pattern ."

Configurable

Once I publish the written JavaScript code to this world, someone wants to modify it, it is usually because people want it to complete some tasks that it cannot do, but it is usually because the programs I write are not flexible enough to provide user-defined functions. The solution is to add a configuration item object to your script. I have written an article about JavaScript configuration item objects in depth. The following are the key points:

---- Add an object named configuration in your script.
---- This object stores all the things that people often change when using this script:
** Css id and class name;
** Button name, tag word, etc;
** For example, "number of images displayed per page" and "size of images displayed;
** Location, location, and language settings.
---- Return this object as a public property to the user so that the user can modify and overwrite it.
This is usually the last step in your programming process. I put these sets in an example: "Five things to do to a script before handing it over to the next developer ."

In fact, you also hope that your code can be used in a very good way, and make some changes according to their own needs. If you implement this function, you will receive fewer emails that may confuse you from people complaining about your script. These emails will tell you, someone has modified your script and it is easy to use.

Interaction with the background

One important thing I have learned from so many years of programming experience is that JavaScript is an excellent language for interface interaction. However, if it is used to process numbers or access data sources, that's a little hard work.

At first, I learned JavaScript to replace Perl, because I hate to copy the code to the cgi-bin folder to run Perl. Later, I realized that a language working in the background should be used to process the main data, rather than letting JavaScript do everything. More importantly, we need to consider security and language features.

If I access a Web service, I can get data in JSON-P format, and in the client browser I convert it to a variety of data, but when I have a server, I have more methods to convert data. On the Server side, I can generate JSON or HTML format data and return it to the client, as well as cache data. If you have learned and prepared this in advance, you will gain long-term benefits and save a lot of time for headaches. Writing a program for various browsers is a waste of time. Use the Toolkit!

When I first started Web development, I struggled for a long time on whether to use document. all or document. layers when accessing pages. I chose document. layers, because I like the idea that every layer is its own document (and I write too many documents. write to generate elements ). The layer mode eventually fails, so I began to use document. all. I'm glad to announce that Netscape 6 only supports W3C DOM models, but users are not concerned about this. Users just see that this browser cannot display what most browsers can display normally-this is our encoding problem. We have compiled short-sighted code that can only run in the current environment. Unfortunately, our runtime environment is constantly changing.

I have wasted too much time dealing with compatibility with various browser versions. Being good at solving such problems offers me a good job opportunity. But now we don't have to endure this kind of pain.

Some toolkit, such as YUI, jQuery, and Dojo, can help us deal with such problems. They use abstract interfaces to solve various browser problems, such as version incompatibility and design defects, to free us from pain points. Unless you want to test a browser of a Beta version, do not add code to your own program to correct the browser's defects, because it is very likely that when the browser has modified this problem, you forgot to delete your code.

On the other hand, relying entirely on the Toolkit is also short-sighted. The Toolkit can help you develop quickly, but if you do not have a deep understanding of JavaScript, you will also do something wrong.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.