7 JavaScript tips that should have been known _javascript tips

Source: Internet
Author: User
Tags event listener mathematical functions

I've been writing JavaScript code for a long time and I can't remember when it started. I am very excited about the achievements of JavaScript as a language in recent years, and I am fortunate to be the beneficiaries of these achievements. I have written a lot of articles, chapters, and a book devoted to it, but I can still find some new knowledge about the language. The following description is the past that I can't help but send out "Ah!" "The exclamation of programming tips, these tips you should try now, rather than waiting for some time in the future to find them by chance.

Concise wording

One of my favorite things in JavaScript is the shorthand method for generating objects and arrays. In the past, if you want to create an object, you need to do this:

Copy Code code as follows:

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

The following writing can achieve the same effect:
Copy Code code as follows:

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


Much simpler, you don't have to use the name of this object over and over again. So the car is defined, maybe you will encounter invaliduserinsession problems, which only you will encounter when using IE, as long as you remember, do not write a comma in front of the right curly braces, you will not have trouble.

Another handy shorthand is for arrays. The traditional way of defining arrays is this:

Copy Code code as follows:

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

The short version is this:
Copy Code code as follows:

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

For arrays, there is a problem, but there is no graph group function. But you'll often find someone who defines the car on top, like this.
Copy Code code as follows:

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


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

Another very cool shorthand method is to use the ternary conditional notation. You don't have to write the following ...

Copy Code code as follows:

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


You can use the ternary conditional notation to simplify it:

Copy Code code as follows:

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

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

Storing data in JSON form

Before I found JSON, I used a variety of crazy methods to store data in JavaScript's intrinsic data types, such as arrays, strings, and the middle with symbols that were easy to split and other annoying things. After Douglas Crockford invented the JSON, everything changed. With JSON, you can use JavaScript's own functionality to store data in a complex format without having to do other additional transformations that can be accessed directly. JSON is the abbreviation for "JavaScript Object notation", which uses the two shorthand methods mentioned above. So, if you want to describe a band, you might write like this:

Copy Code code 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 use JSON directly in JavaScript, and you can encapsulate it in a function, even as a return value form for an API. We call this json-p, and many APIs use this form.

You can call a data supply source and return json-p data directly in the script code:

Copy Code code 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 (' delicious '). InnerHTML = out;
}
</script>
<script src= "Http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious" ></ Script>


This is the list of recent unordered bookmarks in JSON format that calls the Web Service feature provided by the delicious Web site.

Basically, JSON is the lightest way to describe a complex data structure, and it can run in a browser. You can even use the Json_decode () function in PHP to run it. JavaScript's own functions (math, Array, and String) One of the things that surprises me is that when I look at the math and string functions in JavaScript, I find that they can greatly simplify my programming work. Using them, you can dispense with complex loops and conditional judgments. For example, when I need to implement a function to find the largest number in a numeric array, I used to write this loop like this:

Copy Code code as follows:

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 do without loops:
Copy Code code as follows:

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

Note that you cannot sort () a numeric character array, because in this case it will only be sorted alphabetically. If you want to know more usage, you can read this good article about sort ().

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

Copy Code code as follows:

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

Because this function verifies the number and returns the largest one, you can use it to test the browser's support for an attribute:
Copy Code code as follows:

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 attributes will hold the value, and the other will be undefined, so you can get this number by using Math.max (). Read this article and you'll get more knowledge about using mathematical functions to simplify JavaScript.

Another function that has a very useful string of operations is split () and join (). I think the most representative example should be to write a feature that is used to attach CSS styles to page elements.

So, when you attach a CSS class to a page element, either it's the first CSS class for the element, or it has some class, you need to add a space to the existing class, and then append the class. And when you want to remove this class, you also need to remove the space in front of the class (this is important in the past, because some older browsers do not know the class with the following spaces).

So, the original wording would be this:

Copy Code code as follows:

function AddClass (elm,newclass) {
var c = elm.classname;
Elm.classname = (c = = "")? Newclass:c+ ' +newclass;
You can perform this task automatically using the split () and join () functions:

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 that the class you want to append is exactly the last.

Event delegation

Web applications are run by event-driven. I like event handling, especially I like to define events myself. It allows you to expand your product without changing the core code. There is a big problem (or a powerful performance), and it's about the removal of events on the page. You can install an event listener on an element, and the event listener starts working. But there is no indication on the page that there is a listener. Because of the problem of not being able to perform (which in particular gives some novice headaches), and "browsers" like IE6, which have a variety of memory problems when using event monitoring too much, you have to admit that it is wise to minimize the use of event programming.

So the event delegation appeared.

When an event on an element on the page is triggered, in a DOM inheritance relationship, all of the child elements of this element can also receive this event, and you can use an event handler on the parent element instead of using the event listener on each of the various child elements of the stack. What exactly does that mean? Let's just say, there are a lot of hyperlinks on the page, you don't want to use these links directly, you want to call the link through a function, the HTML code is this:

Copy Code code as follows:

<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 to each link by looping through these links:

Copy Code code as follows:

Typical event-handling examples
(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 this is clicked
alert (x);
E.preventdefault ();
};
})();

We can also accomplish this task with an event handler:
Copy Code code as follows:

(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 happen in these page elements, all you have to do is compare their nodename and find the element that should respond to the event.

Disclaimer: These two examples of events are available in all browsers, except for IE6, where you need to use an event model instead of a simple IE6 standard implementation. This is why we recommend using some toolkits.

The benefits of this approach are not limited to reducing multiple event handlers to one. You think, for example, you need to dynamically append more links to the link table. When you use an event delegate, you don't need to make any other changes; otherwise, you will need to recycle the linked table and reinstall the event handler for each link.

anonymous functions and modularity

The most frustrating 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 global, which means that other scripts on the page can also access it and overwrite 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 notation will result in three global variables and two global functions:

Copy Code code as follows:

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

If there is a variable called status in other scripts on this page, the trouble arises. If we encapsulate them in a myapplication, the problem is solved:
Copy Code code as follows:

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, it's OK. You can also omit the name of the function:
Copy Code code as follows:

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

If you want to be able to use something outside of a function, make some changes. In order to be able to access createmember () or getmemberdetails (), you need to turn them into MyApplication properties, exposing them to the outside world:
Copy Code code as follows:

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.
[Code]
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 patterns so that functions and variables can be accessed by the outside world. What's more, I need to add the MyApplication prefix when calling. So, I don't like to do this, I prefer to simply put the pointers to the elements that need to be accessed by the outside world. By doing so, it simplifies the way the outside calls are written:
[Code]
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 post the JavaScript code in the world, someone wants to change it, usually because people want it to do something that it can't do itself-but it's usually the program I write that isn't flexible enough to provide user-customizable functionality. The solution is to add a configuration item object to your script. I've written an article that delves into the JavaScript configuration item object, and here's the main points:

In your script you add an object called configuration.
In this object, it holds all the things that people often change when they use this script:
CSS ID and class name;
The name of the button, the sign and so on;
A value such as "Number of pictures per page", "size of the image displayed";
Location, location, and language settings.
Returns this object as a common property to the user, so that the user can modify overwriting it.
This is usually the last thing you need to do in the process of programming. I've shown this in one example: "Five things to a script before handing it over to the next developer."

In fact, you also want your code to be used by people in a very different way, and make some changes according to their needs. If you implement this feature, you will receive less confusing emails from people who complain about your script, which will tell you that someone has modified your script and is working well.

Interacting with the background

One of the important things I've learned in all these years of programming experience is that JavaScript is a very good language for developing interface interactions, but it's a bit Ober if you're working with numbers or accessing data sources.
Initially, I studied JavaScript as a substitute for Perl because I hated the need to copy the code to the Cgi-bin folder to make Perl run. Later, I learned that you should use a background-working language to handle the main data, rather than having JavaScript do everything. More importantly, we have to consider security and language features.

If I have access to a Web service, I can get data in the JSON-P format, I do a variety of data transformations in the client browser, but when I have the server, I have more ways to transform the data. I can generate JSON or HTML-formatted data on the server side to return to the client and cache data. If you know beforehand and prepare for these, you will gain long-term benefits, save a lot of headaches time. It's a waste of time to write a program that works for a variety of browsers, using a toolkit!

When I first started web development, I struggled for a long time to use document.all or document.layers when I visited the page. I chose Document.layers, because I like the idea that any layer is my own document (and I write too many document.write to generate elements). Layer mode eventually failed, so I started using document.all. I'm happy when Netscape 6 announces that only the DOM model is supported, but users don't really care. The user simply sees that the browser does not show what most browsers are capable of displaying-this is our coding problem. We have written short-sighted code that can only run in the current environment, and unfortunately, our environment is constantly changing.

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

Some toolkits, such as YUI, JQuery, and dojo, can help us deal with this kind of problem. They deal with browser problems by abstracting various interface implementations, like version incompatibility, design flaws, and so on, freeing us from pain. Unless you're testing a beta browser, don't add code that fixes the bug in your app, because you're likely to forget to delete your code when the browser has changed the problem.

On the other hand, relying entirely on toolkits is also a short-sighted act. Toolkits can help you develop quickly, but if you don't understand JavaScript in depth, you'll do the wrong thing.

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.