Seven details for beginners of JavaScript

Source: Internet
Author: User

Each language has a special place. For JavaScript, using var can declare any type of variables. This script language looks very simple, however, to write elegant code, you need to constantly accumulate experience. This article lists seven details that JavaScript Beginners should pay attention.
(1) simplified code
It is very simple to define objects and arrays in JavaScript. We want to create an object, which is generally written as follows:
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
}

The subsequent statement is much shorter, and you do not need to repeat the object name.
In addition, there is a simple way to write arrays. In the past, we declared arrays as follows:
Copy codeThe Code is as follows:
Var moviesThatNeedBetterWriters = new Array (
'Transformers ', 'transformers2', 'Avatar', 'Indiana Jones 4'
);

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

For arrays, there is also a special thing like associating arrays. You will find that many codes define objects as follows:
Copy codeThe Code is as follows:
Var car = new Array ();
Car ['color'] = 'red ';
Car ['wheels'] = 4;
Car ['hubcaps'] = 'spinning ';
Car ['age'] = 4;

This is crazy. Don't be confused. "Join array" is just an alias of an object.
Another way to simplify the code is to use the ternary operator. For example:
Copy codeThe Code is as follows:
Var direction;
If (x <200 ){
Direction = 1;
} Else {
Direction =-1;
}

We can replace this statement with the following code:
Copy codeThe Code is as follows: var direction = x <200? 1:-1;
(2) Use JSON as the data format
The great Douglas Crockford invented the JSON data format to store data. You can use the native javascript method to store complex data without any extra conversion. For example:
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 use JSON directly in JavaScript, or even as a format returned by the API, which is applied in many APIs, for example:
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>

Call delicious's Web service to obtain the latest bookmarks, return them in JSON format, and display them as Unordered Lists.
In essence, JSON is the most lightweight way to describe complex data and runs directly in a browser. You can even call the json_decode () function in PHP to use it.
(3) Try to use JavaScript native functions
To find the maximum number in a group of numbers, we may write a loop, for example:
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 );

In fact, the same function can be implemented without loops:
Copy codeThe Code is as follows:
Var numbers = [3,342, 124,];
Numbers. sort (function (a, B) {return B-});
Alert (numbers [0]);

The simplest method is:
Copy codeCode: Math. max (12,123, 433, 433,4); // returns
You can even use Math. max to check the attributes supported by the browser:
Copy codeThe Code is as follows:
Var scrollTop = Math. max (
Doc.doc umentElement. scrollTop,
Doc. body. scrollTop
);

If you want to add a class style to an element, the original method may be as follows:
Copy codeThe Code is as follows:
Function addclass (elm, newclass ){
Var c = elm. className;
Elm. className = (c = '')? Newclass: c + ''+ newclass;

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

(4) event Delegation
Events are a very important part of JavaScript. We want to bind a click event to a link in the list. The general practice is to write a loop and bind events to each link object. 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>

The script is as follows:
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 ();
};
})();

A more reasonable statement is to bind only events to the parent object of the list. The Code is as follows:
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 ();
}
};
})();

(5) Anonymous Functions
One of the biggest headaches about JavaScript is that its variables do not have a specific scope. Generally, all variables, functions, arrays, or objects are global, which means other scripts on the same page can access and overwrite them. The solution is to encapsulate variables in an anonymous function. For example, the following definition 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 (){
// [...]
}

The package is as follows:
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 called the standalone mode and is a JavaScript design mode. This mode is widely used in YUI. The improved syntax is as follows:
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.

(6) configurable code
You can configure the Code to make it easier for others to use or modify. The solution is to add a configuration object to the script you write. Key points are as follows:
1. Add an object named configuration in your script.
2. store all the things that others may want to change in the configuration object, such as css id, class name, and language.
3. Return this object as a public attribute so that others can rewrite it.
(7) code compatibility
Compatibility is easy for beginners to ignore. Generally, Javascript is tested in a fixed browser, and this browser is probably IE, which is very fatal, this is because IE currently has the worst standard support among several mainstream browsers. The end user may see that the code you write cannot run correctly in a browser. You should test your code in mainstream browsers. This may be time-consuming, but it should be done.

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.