7 JavaScript tricks you should know [go]

Source: Internet
Author: User
Tags event listener mathematical functions

Concise notation

Shorthand for objects
In the past, if you wanted to create an object, you needed this:

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

The following writing can achieve the same effect:

var car = {
Colour: ' Red ',
Wheels:4,
Hubcaps: ' Spinning ',
Age:4
}

This is much easier, and you don't have to reuse the name of the object.
So car is defined, perhaps you will encounter invaliduserinsession problem, this only you will encounter when using IE, just remember a little, do not write a semicolon in front of the curly brace, you will not have trouble.

Shorthand for arrays

The traditional way to define arrays is this:

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

The abbreviated version is this:

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

For arrays, there is a problem here, in fact, there is no graph group function. But you will often find that someone defines the car above like this:

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

arrays are not omnipotent; it is confusing to write them wrong. The graph group is actually the function of the object, and people confuse the two concepts.

Shorthand for ternary conditional symbols

Another very cool shorthand method is to use with ternary conditional notation.
You don't have to write it like this:

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

You can use the ternary conditional notation to simplify it:

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

When the condition is true , take the value after the question mark, or take the value after the colon.

Storing data in JSON form

After Douglas Crockford invented JSON, it all changed.
Using JSON, you can use JavaScript's own functionality to store data in complex formats without the need for additional conversions that can be accessed directly.

JSON is the abbreviation for "JavaScript Object Notation", which uses the two shorthand methods mentioned above.

If you want to describe a band, you might write 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 use JSON directly in JavaScript to encapsulate it in a function, even as a return value for an API.
We call this json-p, and many APIs use this form.
You can call a data supply source and return the JSON-P data directly in the 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 the Web Service feature that is called by the Delicious Web site to get a list of the most recent unordered bookmarks in JSON format.

Basically, JSON is the lightest way to describe complex data structures, and it can be run in a browser. You can even run it in PHP with the Json_decode () function.

JavaScript's own function (Math, Array, and String)

After math and string functions in JavaScript, I find that they can greatly simplify my programming work. Using them, you can eliminate complex cyclic processing and conditional judgments.

For example, when you need to implement a function to find the largest number in a 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);

It can be achieved without loops:

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

It is important to note that you cannot do a numeric character array sort() , because in this case it will only be sorted in alphabetical order.
If you want to know more about the usage, you can read this nice sort() article about it.

One more interesting function is Math.max() .
This function returns the largest number in the number in the argument:

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:

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 depending on the DOCTYPE on the page, only one of these two properties will hold this value, and the other will be undefined, so you can get this number by using Math.max ().
Reading this article will give you more knowledge about using mathematical functions to simplify JavaScript.

Another function that has a pair of very useful action strings is split () and join (). I think the most representative example would be to write a function that attaches a CSS style to the page element.

So, when you attach a CSS class to a page element, either it's the first CSS class for that element, or it already has some class
, you need to add a space to the existing class and append the class. And when you want to get rid of this class, you also need to remove the space in front of this class (this is very important in the past, because some old browsers do not know the class that followed the space).

So, the original wording would be this:

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

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

function AddClass (elm,newclass) {
var classes = Elm.className.split (");
Classes.push (Newclass);
Elm.classname = Classes.join (");
}

This will ensure that all classes are separated by spaces, and that the class you want to append is exactly the last one.

Event delegation

Web applications are event-driven. I like event handling, and I especially like defining events myself.
It allows you to expand your product without having to change the core code.
There is a big problem (and it can be said to be a powerful performance) about the removal of events on the page. You can install an event listener on an element, and the event listener will begin to function.
But there is no indication on the page that there is a listener. Because of this non-expressive problem (which in particular makes some novice headaches) and a "browser" like IE6, there are a variety of memory problems when listening to too many usage events, you have to admit that using event programming as little as possible is a smart idea.

Then the event delegation appeared.
When an event on an element on a page is triggered, and on the DOM inheritance, all child elements of the element can also receive this event, you can use an event handler on the parent element to process it instead of using an event listener on a bunch of individual child elements.

What exactly does that mean? In this case, there are a lot of hyperlinks on the page, you don't want to use these links directly, you want to call this link through a function, the HTML code is:

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

It is common practice to attach an event handler on each link by looping through these links:

Typical example of event handling
(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 ();
};
})();

We can also accomplish this task with an event handler:

(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 have to do is compare them to nodeName find the element that should respond to the event.

Disclaimer: The above-mentioned two examples of events, in all browsers can be run, in addition to IE6, on the IE6 you need to use an event model, rather than a simple standard implementation of the Web. This is why we recommend using some toolkits.

The benefit of this approach is not limited to reducing the number of event processors to one. You think, for example, you need to dynamically add more links to the link table. With the event delegate, you do not need to make any other changes, otherwise you will need to re-loop the link table and re-install the event handler for each link.

anonymous functions and modularity

The most annoying thing in JavaScript is that variables are not in use. Any variable, function, array, object, as long as it is not inside the function, is considered to be global, that is to say, the other script on this page can also access it, and can override it.

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

var name = ' Chris ';
var age = ' 34 ';
var status = ' single ';

function Createmember () {
// [...]
}

function Getmemberdetails () {
// [...]
}

If there is a variable called in the other scripts on this page status , the trouble arises.
If we encapsulate them in one myApplication , the problem is solved:

var myapplication = function () {
var name = ' Chris ';
var age = ' 34 ';
var status = ' single ';

function Createmember () {
// [...]
}
function Getmemberdetails () {
// [...]
}
}();

However, there is no function outside of the function. If that's what you need, then it's okay.

You can also omit the name of the function:

(function () {
var name = ' Chris ';
var age = ' 34 ';
var status = ' single ';

function Createmember () {
// [...]
}
function Getmemberdetails () {
// [...]
}
})();

If you want to use the inside of the function, you need to make some changes.

To be able to access createmember () or getmemberdetails (), you need to turn them into MyApplication properties, exposing them to the outside world:

var myapplication = function ()
{
var name = ' Chris ';
var age = ' 34 ';
var status = ' single ';

return{
Createmember:function () {
// [...]
},
Getmemberdetails:function () {
// [...]
}
}
}();
Myapplication.createmember () and
Myapplication.getmemberdetails () is ready to use.

This is called module mode or singleton.

Douglas Crockford Many times talked about these, Yahoo user Interface Library YUI in this has a lot of use. But what makes me uncomfortable is that I need to change the sentence to make the functions and variables accessible to the outside world. What's more, I need to add myapplication to this prefix when I call them. So, I don't like to do that, I prefer to simply give pointers to the elements that need to be accessible by the outside world. This simplifies the way outside calls are made:

var myapplication = function ()
{
var name = ' Chris ';
var age = ' 34 ';
var status = ' single ';

function Createmember () {
// [...]
}

function Getmemberdetails () {
// [...]
}

return{
Create:createmember,
Get:getmemberdetails
}
}();
Now write Myapplication.get () and Myapplication.create () on the line.

I call this "revealing module pattern."

Configurable

Once I've posted the JavaScript code in this world, someone wants to change it, usually people want it to do something that it doesn't do-but usually it's not flexible enough to provide user-definable functionality.

The workaround is to add a configuration item object to your script.
I have written an in-depth article about JavaScript configuration item objects, and here are some of the key points:

@ Add a named object to your script. configuration
@ This object, store all the things people often change when they use this script:
* CSS ID and class name;
* The name of the button, sign and so on;
* Values such as "Number of pictures per page", "Size of image displayed";
* Locations, location, and language settings.
@ returns this object as a common property to the user so that the user can modify it to overwrite it.

Usually this is the last thing you need to do in your programming process. I concentrated on this in one example: "Five things to does to a script before handing it-to-the-next developer."

In fact, you want your code to be used in a way that makes people use it and make changes to their needs.
If you do this, you will receive fewer emails from people complaining about your script that will tell you that someone has modified your script and that it works well.

Interacting with the background

One of the important things I've learned over the years of programming is that JavaScript is a great language for developing interface interactions, but if you're working with numbers or accessing data sources, it's a bit retwist.

At first, I learned to use JavaScript as a replacement for Perl because I hated the fact that I had to copy the code to a cgi-bin folder for Perl to run.
Later, I realized that I should use a background working language to deal with the main data, and not to let JavaScript do everything. More importantly, we have to consider security and language features.

If I visit a Web service, I can get the data into the json-p format, in the client browser I do a variety of data conversion, but when I have the server, I have more ways to transform the data, I can generate JSON or HTML-formatted data back to the client on the server side, as well as caching the data.
If you know it beforehand and prepare for it, you will have long-term benefits and save a lot of headaches.

Writing programs that apply to various browsers is a waste of time, use a toolkit!

When I first started web development, I struggled with the document.all pain of using or using the pages when I visited document.layers them.
I chose document.layers , because I like the idea that any layer is my own document (and I wrote too many document.write to generate elements).
Layer mode eventually failed, so I started using document.all .
I was happy when Netscape 6 announced support for the DOM model only, but the user didn't really care.
The user simply sees that this browser does not show what most browsers are capable of displaying properly-this is the problem with our coding.
We write short-sighted code that only runs in the current environment, and unfortunately our operating environment is constantly changing.

I've wasted too much time dealing with issues that are compatible with various versions of various browsers.
Being good at dealing with such problems provides me with a good job opportunity. But now we don't have to endure this pain.

Some toolkits, such as YUI, JQuery, and Dojo, can help us deal with this kind of problem.
They solve various browser problems by abstracting various interface implementations, such as incompatible versions, design flaws, and so on, freeing us from pain.
Unless you want to test a beta version of the browser, do not add code to fix the bug in your browser, because you most likely when the browser has modified the problem, you forgot to delete your code.

On the other hand, full reliance on toolkits is also a short-sighted behavior. The toolkit can help you develop quickly, but you'll do the wrong thing if you don't understand JavaScript in depth.

Original address:http://www.smashingmagazine.com/2010/04/20/seven-javascript-things-i-wish-i-knew-much-earlier-in-my-career/

Reprint Address:http://www.aqee.net/2010/05/06/seven-javascript-things-i-wish-i-knew-much-earlier-in-my-career/

7 JavaScript tricks you should know [go]

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.