Some neighborhood JavaScript skills

Source: Internet
Author: User

The success of JavaScript is repeat. Writing JavaScript code for Web pages is already the basic skill of all Web designers. This interesting language contains many unfamiliar things, even if JavaScript programmers who have been writing JavaScript for many years, not completely thorough. This article describes seven tips that are not familiar with but useful in JavaScript.
Simple statement
JavaScript can use simple statements to quickly create objects and arrays, such as the following code:
Copy codeThe Code is as follows:
Var car = new Object ();
Car. color = 'red ';
Car. wheels = 4;
Car. hubcaps = 'spinning ';
Car. age = 4;

You can use the following simple statement:
Copy codeThe Code is as follows:
Var car = {
Color: 'red ',
Wheels: 4,
Hubcaps: 'spinning ',
Age: 4
}

The object car is created here, but note that do not add ";" before ending the curly brackets; "Otherwise, it will be very troublesome for IE.
The traditional method for creating arrays is:
Copy codeThe Code is as follows:
Var moviesThatNeedBetterWriters = new Array (
'Transformers ', 'transformers2', 'Avatar', 'Indiana Jones 4'
);

Use the simple statement:

Copy codeThe Code is as follows:
Var moviesThatNeedBetterWriters = [
'Transformers ', 'transformers2', 'Avatar', 'Indiana Jones 4'
];

Another question about arrays is whether there is an associated array. You will find a lot of code examples to define examples like this on the car
Copy codeThe Code is as follows:
Var car = new Array ();
Car ['color'] = 'red ';
Car ['wheels'] = 4;
Car ['hubcaps'] = 'spinning ';
Car ['age'] = 4;


Another simple statement that can be used is the condition judgment statement:
Copy codeThe Code is as follows:
Var direction;
If (x <200 ){
Direction = 1;
} Else {
Direction =-1;
}

It can be simply as follows:
Copy codeThe Code is as follows: var direction = x <200? 1:-1;

JSON Data Format
JSON, short for "JavaScript Object Notation", is designed by Douglas Crockford. JSON changes the difficulty of JavaScript in caching complex data formats. For example, if you want to describe a band, you can write as follows:
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, or even return data objects as some APIs. The following code calls an API of delicious.com, the famous bookmarkdon.com, and returns all your bookmarks on the website, and displayed on your own website:
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>


JavaScript local functions (Math, Array, and String)
JavaScript has many built-in functions, which can be effectively used to avoid a lot of unnecessary Code. For example, to find the maximum value from an array, the traditional method is:
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 );

Using built-in functions can be easier to implement:
Copy codeThe Code is as follows:
Var numbers = [3,342, 124,];
Numbers. sort (function (a, B) {return B-});
Alert (numbers [0]);

Another method is to use the Math. max () method:
Copy codeThe Code is as follows:
Math. max (12,123, 433, 433,4); // returns

You can use this method to detect browsers
Copy codeThe Code is as follows:
Var scrollTop = Math. max (
Doc.doc umentElement. scrollTop,
Doc. body. scrollTop
);

This solves the problem of IE browser. In this way, you can always find the correct value, because the value not supported by the browser will return undefined.
You can also use the JavaScript built-in split () and join () functions to process the CSS class names of HTML objects. If the class names of HTML objects are separated by spaces, when you append or delete a CSS class name for the object, you must note that if the object does not have the class name attribute, you can directly assign the new class name to it, if a class name already exists, there must be a space before the new class name, which is implemented using the traditional JavaScript method as follows:
Copy codeThe Code is as follows:
Function addclass (elm, newclass ){
Var c = elm. className;
Elm. className = (c = '')? Newclass: c + ''+ newclass;
}

Using the split and join methods is more intuitive and elegant:
Copy codeThe Code is as follows:
Function addclass (elm, newclass ){
Var classes = elm. className. split ('');
Classes. push (newclass );
Elm. className = classes. join ('');
}

Event proxy
Instead of designing a bunch of events in the HTML document, it is better to directly design an event proxy. 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 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>

Traditional event processing is to traverse various links and add corresponding event processing:
Copy codeThe Code is 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.tar get; // Get the link that was clicked
Alert (x );
E. preventDefault ();
};
})();

With event proxy, you can directly process it without traversing:
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 ();
}
};
})();

Anonymous function and Module Mode
One problem with JavaScript is that any variable, function, or object, unless defined within a function, is global, this means that other code on the same web page can access and rewrite this variable (ECMA's JavaScript 5 has changed this situation-the translator). Using anonymous functions, you can bypass this issue.
For example, if you have such a piece of code, obviously, the variables name, age, and status will become global variables.
Copy codeThe Code is as follows:
Var name = 'chris ';
Var age = '34 ';
Var status = 'singles ';
Function createMember (){
// [...]
}
Function getMemberDetails (){
// [...]
}

To avoid this problem, you can use the anonymous function:
Copy codeThe Code is as follows:
Var myApplication = function (){
Var name = 'chris ';
Var age = '34 ';
Var status = 'singles ';
Function createMember (){
// [...]
}
Function getMemberDetails (){
// [...]
}
}();

If this function is not called, you can directly:
Copy codeThe Code is as follows:
(Function (){
Var name = 'chris ';
Var age = '34 ';
Var status = 'singles ';
Function createMember (){
// [...]
}
Function getMemberDetails (){
// [...]
}
})();

To access the objects or functions, you can:
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 () now works.


This is the so-called Module mode or Singleton mode, which is favored by Douglas Crockford and widely used in Yahoo User Interface Library YUI.
If you want to call the methods in other places and do not want to use the object name myApplication before calling, you can return these methods in the anonymous function, or even return them in short:
Copy codeThe Code is as follows:
Var myApplication = function (){
Var name = 'chris ';
Var age = '34 ';
Var status = 'singles ';
Function createMember (){
// [...]
}
Function getMemberDetails (){
// [...]
}
Return {
Create: createMember,
Get: getMemberDetails
}
}();
// MyApplication. get () and myApplication. create () now work.

Code Configuration
When others use the JavaScript code you write, it is inevitable that some code will be changed, but this will be very difficult, because not everyone can easily understand others' code, it is better to create a code configuration object. Others only need to modify some configurations in this object to implement code changes. Here is a detailed explanation of the JavaScript configuration object, to put it simply:

· Create an object named configuration in the code

· Save all configuration changes, such as css id and class name, button label text, descriptive text, and localization language settings.

· Set this object as a global object for direct access and rewriting by others

You should do this in the last step. Here is an article for the reference of the five values before the code is delivered.
Interaction with the background
JavaScript is a front-end language. You need other languages to interact with the background and return data. with AJAX, you can allow JavaScript to directly use the interaction with the background and process complex data in the background.
JavaScript framework
Writing your own code to adapt to various browsers is a waste of time. You should select a JavaScript framework to let these complicated tasks be handled by the framework.
More resources

· Douglas Crockford on JavaScript
JavaScript deep video tutorial

· The Opera Web Standards Curriculum
JavaScript details

Additional reading

· 10 confusing things about JavaScript

· The New API seeks to allow JavaScript to operate on local files

· Saving HTML5 offline storage with JavaScript

· Open-source projects are increasingly favored by JavaScript

· Is Javascript an error?

· The Future of Javascript 2 is settled

· The top 10 most famous JavaScript libraries in Google's ranking

· ECMA launches JavaScript 5

International Source: Smashing Magazine Seven JavaScript Things I Wish I Knew Much Earlier In My Career (Author: Christian Heilmann)

[This is from the deep blue residence in the blog Park. Please indicate the author's source for reprinting]

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.