JavaScript Beginner: Seven details to be noticed by JavaScript beginners

Source: Internet
Author: User
Tags add format anonymous array arrays object variables variable



each language has its own special place, for JavaScript, the use of Var can declare any type of variable, the scripting language seems very simple, but to write elegant code is the need for continuous accumulation of experience. This article provides a list of seven details that JavaScript beginners should pay attention to, and share them with you.


(1) simplifies code


JavaScript defines objects and arrays very simply, and we want to create an object that is generally written like this:
1 var car = new Object ();
2 Car.colour = ' red ';
3 Car.wheels = 4;
4 Car.hubcaps = ' spinning ';
5 Car.age = 4;
the following wording can achieve the same effect:
1 var car = {
2 Colour: ' Red ',
3 Wheels:4,
4 Hubcaps: ' Spinning ',
5 Age:4
The
6 }
is much shorter, and you don't have to repeat the object name.


also has a concise way of writing the array, which we have declared in the past:
1 var moviesthatneedbetterwriters = new Array (
2 ' Transformers ', ' Transformers2 ', ' Avatar ', ' Indiana Jones 4 '
3 );
more concise writing is:
1 var moviesthatneedbetterwriters = [
2 ' Transformers ', ' Transformers2 ', ' Avatar ', ' Indiana Jones 4 '
3 ];
for arrays, there is an associative array of such a special thing. You'll find that a lot of code defines objects like this:
1 var car = new Array ();
2 car[' colour '] = ' red ';
3 Car[' wheels '] = 4;
4 car[' hubcaps '] = ' spinning ';
5 car[' age ' = 4;
This is crazy, don't be confused, associative array is just an alias for an object.


another way to simplify the code is to use the ternary operator, for example:
1 var direction;
2 if (x < 200) {
3 Direction = 1;
4 } else {
5 Direction =-1;
6 }
we can use the following code to replace this type of notation:
1 var direction = x < 200? 1:-1;
 


(2) uses JSON as the data format


great Douglas Crockford invented the JSON data format to store data, you can use native JavaScript methods to store complex data without any additional transformations, such as:
01 var band = {
02 "Name": "The Red Hot Chili Peppers",
03 "Members": [
04 {
05 "Name": "Anthony Kiedis",
06 ' Role ': ' Lead vocals '
07 },
08 {
09 "Name": "Michael ' Flea ' Balzary",
10 "Role": "Bass guitar, trumpet, backing vocals"
11 },
12 {
13 "Name": "Chad Smith",
14 "Role": "Drums,percussion"
15 },
16 {
17 "Name": "John Frusciante",
18 ' Role ': ' Lead Guitar '
19 }
20 ],
21st "Year": "2009"
22 }
you can use JSON directly in JavaScript, or even a format returned as an API, to be applied in many APIs, such as:
01 <div id= "Delicious" ></div><script>
02 function Delicious (o) {
03 var out = ' <ul> ';
04 for (Var i=0;i<o.length;i++) {
05 out = = ' <li><a href= ' + o[i].u + ' > ' +
06 O[I].D + ' </a></li> ';
07 }
08 Out + = ' </ul> ';
09 document.getElementById (' delicious '). InnerHTML = out;
10 }
11 </script>
12 <script src= "Http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious" ></ Script>
here, call the delicious Web service to get the latest bookmarks, return in JSON format, and then display them in the form of unordered lists.


Essentially, JSON is the most lightweight way to describe complex data, and it runs directly in the browser. You can even call the Json_decode () function in PHP to use it.


(3) Try to use JavaScript native function


to find the largest number in a set of numbers, we might write a loop, for example:
1 var numbers = [3,342,23,22,124];
2 var max = 0;
3 for (Var i=0;i<numbers.length;i++) {
4 if (Numbers[i] > max) {
5 max = Numbers[i];
6 }
7 }
8 Alert (max);
in fact, do not have to loop to achieve the same function:
1 var numbers = [3,342,23,22,124];
2 Numbers.sort (function (a,b) {returnb-a});
3 Alert (numbers[0]);
and the most concise writing is:
1 Math.max (12,123,3,2,433,4); Returns 433
you can even use Math.max to detect which attributes the browser supports:
1 var scrolltop= math.max (
2 Doc.documentElement.scrollTop,
3 Doc.body.scrollTop
4 );
If you want to add a class style to an element, it might be the original way of writing:
1 function AddClass (elm,newclass) {
2 var c = elm.classname;
The
3 Elm.classname = (c = = "")? Newclass:c+ ' +newclass;
and more elegant writing is:
1 function AddClass (elm,newclass) {
2 var classes = Elm.className.split (');
3 Classes.push (Newclass);
4 Elm.classname = Classes.join (");
5 }
 


(4) event delegate

The
event is a very important part of JavaScript. We want to bind a link in a list to a point hit event, the general practice is to write a loop, to each linked object binding events, the HTML code is as follows:
1
2 <ul id= "Resources" >
3 <li><a href= "HTTP://OPERA.COM/WSC" >opera WEB standards curriculum</a></li>
4 <li><a href= "http://sitepoint.com" >Sitepoint</a></li>
5 <li><a href= "http://alistapart.com" >a List apart</a></li>
6 <li><a href= "http://yuiblog.com" >yui blog</a></li>
7 <li><a href= "http://blameitonthevoices.com" >blame it on the voices</a></li>
8 <li><a href= "http://oddlyspecific.com" >oddly specific</a></li>
The
9 </ul>
script is as follows:
01 Classic Event Handling Example
02 (function () {
03 var resources = document.getElementById (' resources ');
04 var links = resources.getelementsbytagname (' a ');
05 var all = Links.length;
06 for (Var i=0;i<all;i++) {
07 Attach a listener to each link
08 Links[i].addeventlistener (' click ', Handler,false);
09 };
10 function Handler (e) {
11 var x = E.target; Get the link this is clicked
12 alert (x);
13 E.preventdefault ();
14 };
15 })();
is more reasonable to write only to the parent object of the list to bind the event, the code is as follows:
01 (function () {
02 var resources = document.getElementById (' resources ');
03 Resources.addeventlistener (' click ', Handler,false);
04 function Handler (e) {
05 var x = E.target; Get the link tha
06 if (x.nodename.tolowercase () = = = ' a ') {
07 Alert (' Event delegation: ' + x);
08 E.preventdefault ();
09 }
10 };
11 })();
 


(5) anonymous function

One of the biggest headaches of
about JavaScript is that its variables don't have a specific scope. In general, any variable, function, array, or object is global, which means that other scripts on the same page can access and overwrite them. The workaround is to encapsulate the variable in an anonymous function. For example, the following definition produces three global variables and two global functions:
1 var name = ' Chris ';
2 var age = ' 34 ';
3 var status = ' single ';
4 function Createmember () {
5 // [...]
6 }
7 function Getmemberdetails () {
8 // [...]
9 }
after encapsulation as follows:
01 var myapplication = function () {
02 var name = ' Chris ';
03 var age = ' 34 ';
04 var status = ' single ';
05 return{
06 Createmember:function () {
07 // [...]
08 },
09 Getmemberdetails:function () {
10 // [...]
11 }
12 }
13 }();
14 Myapplication.createmember () and
15 Myapplication.getmemberdetails () now works.
This is called the monomer mode, is a JavaScript design pattern, this pattern in Yui used very much, the improvement is written:
01 var myapplication = function () {
02 var name = ' Chris ';
03 var age = ' 34 ';
04 var status = ' single ';
05 function Createmember () {
06 // [...]
07 }
08 function Getmemberdetails () {
09 // [...]
10 }
11 return{
12 Create:createmember,
13 Get:getmemberdetails
14 }
15 }();
16 Myapplication.get () and myapplication.create () now work.
  


(6) code can be configured


your code if you want to make it easier for others to use or modify, you need to be configurable, and the solution is to add a configuration object to the script that you are writing. The main points are as follows:


 


1, add an object called configuration in your script.


2, in the configuration object to store all other people may want to change things, such as the CSS ID, class name, language and so on.


3, returns this object as a public property so that others can override it.


 


(7) Code compatibility


compatibility is a beginner's easy to ignore part, usually when learning JavaScript is in a fixed browser to test, and this browser is probably IE, this is very fatal, because the current several major browsers, ie to the standard of the support is the worst. What the end user sees may be that the code you write is not working correctly in a browser.   You should test your code in a mainstream browser, which may be time-consuming, but it should be done.


This article links http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20121211/34874.html





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.