Seven JavaScript tips that should have been known

Source: Internet
Author: User
Tags mathematical functions

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:
Copy codeThe Code is as follows:
Var car = new Object ();
Car. color = 'red ';
Car. wheels = 4;
Car. hubcaps = 'spinning ';
Car. age = 4;

The following statement can achieve the same effect:
Copy codeThe Code is as follows:
Var car = {
Color: '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:
Copy codeThe Code is as follows:
Var moviesThatNeedBetterWriters = new Array (
'Transformers ', 'transformers2', 'Avatar', 'indianajones 4'
);

The short version is as follows:
Copy codeThe Code 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
Copy codeThe Code is as follows:
Var car = new Array ();
Car ['color'] = '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...
Copy codeThe Code is as follows:
Var direction;
If (x <200 ){
Direction = 1;
} Else {
Direction =-1;
}


You can use the ternary conditional symbol to simplify it:

Copy codeThe Code is as follows:
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:

Copy codeThe Code is as follows:
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:
Copy codeThe Code is as follows:
<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 ('delicmy'). 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:
Copy codeThe Code is as follows:
Var numbers = [3,342, 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:
Copy codeThe Code is as follows:
Var numbers = [3,342, 124,];
Numbers. sort (function (a, B) {return B-});
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:
Copy codeThe Code is as follows:
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:
Copy codeThe Code is as follows:
Var scrollTop = Math. max (
Doc.doc umentElement. 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:

Copy codeThe Code 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:

Copy codeThe Code is as follows:
<H2> Great Web resources <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>


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

Copy codeThe Code is as follows:
// Typical 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.tar get; // Get the link that was clicked
Alert (x );
E. preventDefault ();
};
})();

We can also complete this task with an event processor:
Copy codeThe Code is as follows:
(Function (){
Var resources = document. getElementById ('resources ');
Resources. addEventListener ('click', handler, false );
Function handler (e ){
Var x = e.tar get; // 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, 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.

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:
Copy codeThe Code is as follows:
Var name = 'chris ';
Var age = '34 ';
Var status = 'singles ';
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:
Copy codeThe Code is as follows:
Var myApplication = function (){
Var name = 'chris ';
Var age = '34 ';
Var status = 'singles ';
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:
Copy codeThe Code is as follows:
(Function (){
Var name = 'chris ';
Var age = '34 ';
Var status = 'singles ';
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:
Copy codeThe Code is as follows:
Var myApplication = function (){
Var name = 'chris ';
Var age = '34 ';
Var status = 'singles ';
Return {
CreateMember: function (){
// [...]
},
GetMemberDetails: function (){
// [...]
}
}
}();
// MyApplication. createMember () and
// MyApplication. getMemberDetails.
[Code]
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:
[Code]
Var myApplication = function (){
Var name = 'chris ';
Var age = '34 ';
Var status = 'singles ';
Function createMember (){
// [...]
}
Function getMemberDetails (){
// [...]
}
Return {
Create: createMember,
Get: getMemberDetails
}
}();
// Now write 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.

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.