Some encounter JavaScript tips _javascript Tips

Source: Internet
Author: User
Tags anonymous
The success of JavaScript is a great relish, writing JavaScript code for Web pages is the basic skill of all web designers, and this interesting language contains many things that are not well known, even for years of JavaScript programmers who have not fully understood them. This article is about 7 aspects of JavaScript that you are not familiar with but very practical techniques.
Brief statement
JavaScript can use abbreviated statements to quickly create objects and arrays, such as the following code:
Copy Code code as follows:

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

You can use the following shorthand statements:
Copy Code code as follows:

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

Object car to create this, but you need to pay special attention to the end of the curly braces must not add ";" otherwise in IE will encounter a lot of trouble.
The traditional way to create arrays is:
Copy Code code as follows:

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

Use abbreviated statements:

Copy Code code as follows:

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

Another question about arrays is whether there is an associative array of such things. You'll find a lot of code examples that define the car above like the example
Copy Code code as follows:

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


Another place where you can use a shorthand statement is a conditional judgment statement:
Copy Code code as follows:

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

can be abbreviated as:
Copy Code code as follows:
var direction = x < 200? 1:-1;


JSON data format
JSON is the acronym for "JavaScript Object notation", designed by Douglas Crockford, and JSON changes the plight of JavaScript in caching complex data formats, as in the following example, if you want to describe a band, you can write:
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, or even as a return data object for some APIs, the following code calls an API for the famous bookmark site delicious.com, returns all of your bookmarks on the site, and displays it on your own site:
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>


JavaScript local functions (Math, Array, and String)
JavaScript has many built-in functions that can be used effectively to avoid a lot of unnecessary code, such as finding the maximum value from an array, the traditional method is:
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);

Using built-in functions can be easier to implement:
Copy Code code as follows:

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

Another method is to use the Math.max () method:
Copy Code code as follows:

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

You can use this method to help probe the browser
Copy Code code as follows:

var scrolltop= math.max (
Doc.documentElement.scrollTop,
Doc.body.scrollTop
);

This solves a problem with IE, in this way, you can always find the correct value, because the browser does not support that value will return to undefined.
You can also use JavaScript's built-in split () and join () functions to handle the CSS class name of an HTML object, and if the HTML object's class name is a space-separated number of names, you need to pay special attention when appending or deleting a CSS class name, if the object does not have a class name , you can give it directly to the new class name, and if you already have a class name, you must have a space before the new class name, which is done with the traditional JavaScript method:
Copy Code code as follows:

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

Using the split and join methods is much more visually elegant:
Copy Code code as follows:

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

Event Agent
Rather than designing a bunch of events in an HTML document, it is better to design an event agent directly, for example, if you have some links, the user does not want to open the link after clicking, but executes an event, the HTML code is as follows:
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>

The traditional event processing is traversing each link, plus the individual event handling:
Copy Code code as follows:

Classic 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.target; Get the link this is clicked
alert (x);
E.preventdefault ();
};
})();

Using the event agent, you can handle it directly without traversing:
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 ();
}
};
})();

Anonymous functions and Module mode
One problem with JavaScript is that any variable, function, or object, unless defined within a function, is global, meaning that other code on the same page can access and rewrite the variable (ECMA's JavaScript 5 has changed this situation-the translator), Using anonymous functions, you can bypass the problem.
For example, you have such a piece of code, obviously, variable name, age, status will become global variables
Copy Code code as follows:

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

To avoid this problem, you can use an anonymous function:
Copy Code code as follows:

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

If this function is not invoked, it can be more directly:
Copy Code code as follows:

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

If you want to access an object or function within it, you can:
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 () now works.


This is the so-called Module mode or single example mode (Singleton), the model is Douglas Crockford, and is widely used in Yahoo User Interface Library YUI.
If you want to call the inside method elsewhere and do not want to use the MyApplication object name before the call, you can return the methods in the anonymous function, even by simply returning:
Copy Code code as follows:

var myapplication = function () {
var name = ' Chris ';
var age = ' 34 ';
var status = ' single ';
function Createmember () {
// [...]
}
function Getmemberdetails () {
// [...]
}
return{
Create:createmember,
Get:getmemberdetails
}
}();
Myapplication.get () and myapplication.create () now work.

Code configuration
It's hard to change some code when someone uses your JavaScript code, but it's difficult because it's not easy for everyone to read someone else's code, so instead of creating a code configuration object, the other person needs to change some configuration in order to make changes to the code. Here is a JavaScript configuration object detailed article, simply said:

· Create an object called configuration in your code

· Inside, save all the configurations you can change, such as CSS ID and class name, button label text, descriptive text, localized language settings

· Set the object as a global object so that others can access it directly and overwrite it

You should do the work in the last step, here is a reference to the article, the value of 5 things before delivering the code.
Interacting with the background
JavaScript is a front language, you need other languages to interact with the background, and return data, using AJAX, you can let JavaScript directly use the interaction with the background, the complex data processing to the background processing.
JavaScript Framework
It is a total waste of time to write your own code that adapts to the various browsers, and you should choose a JavaScript framework that allows these complex things to be handled by the framework.
More Resources

· Douglas Crockford on JavaScript
JavaScript Depth Video Tutorial

· The Opera WEB Standards Curriculum
JavaScript detailed

Extended Reading

· 10 things that are confusing about JavaScript

· New API seeks to have JavaScript manipulate local files

· Let JavaScript save HTML5 's offline storage

· Open source projects favor JavaScript more and more

· Is Javascript a mistake?

· Javascript 2 Future Dust settles

· The 10 most famous JavaScript libraries in Google rankings

· ECMA launches JavaScript 5

This article is from international sources: smashing Magazine Seven JavaScript things I wish I knew much earlier into my Career (original author: Christian Heilmann)

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.