JavaScript beginners should pay attention to seven details summary _javascript tips

Source: Internet
Author: User
Tags anonymous
Each language has its own special place, and for JavaScript, using VAR to declare variables of any type, the scripting language looks simple, but it takes a lot of experience to write elegant code. This article provides a list of seven details that JavaScript beginners should pay attention to, and share them with you.
(1) Simplify the code
JavaScript defines objects and arrays very simply, and we want to create an object that is generally written like 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
}

The writing is much shorter, and you don't have to repeat the object name.
In addition to the array also has a concise writing, in the past we declare that the array is written:
Copy Code code as follows:

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

A more concise formulation is:
Copy Code code as follows:

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

For arrays, there is an associative array of such a special thing. You'll find that a lot of code defines objects like this:
Copy Code code as follows:

var car = new Array ();
car[' colour '] = ' red ';
Car[' wheels '] = 4;
car[' hubcaps '] = ' spinning ';
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:
Copy Code code as follows:

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

We can use the following code to replace this notation:
Copy Code code as follows:
var direction = x < 200? 1:-1;

(2) using JSON as the data format
The great Douglas Crockford invented the JSON data format to store data, and you can use native JavaScript methods to store complex data without any additional transformations, such as:
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 a format that is returned as an API, to be applied in many APIs, such as:
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 calls the delicious Web service to get the latest bookmarks, return in JSON format, and then display them in the form of unordered lists.
In essence, 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) Use JavaScript native function as much as possible
To find the maximum number in a set of numbers, we might write a loop, for example:
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);

In fact, you do not have to loop to achieve the same function:
Copy Code code as follows:

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

And the simplest of these is:
Copy Code code as follows:
Math.max (12,123,3,2,433,4); Returns 433

You can even use Math.max to detect which attributes the browser supports:
Copy Code code as follows:

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

If you want to add a class style to an element, the original wording might be:
Copy Code code as follows:

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

And the more elegant wording is:
Copy Code code 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 link in a list to a hit event, the general practice is to write a loop, to each linked object binding events, 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 script is as follows:
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 ();
};
})();

A more logical formulation is to bind the event to the parent object of the list only, as follows:
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 ();
}
};
})();

(5) anonymous function
One of the most frustrating things 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:
Copy Code code as follows:

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

After the encapsulation is as follows:
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 called the monomer mode, is a JavaScript design pattern, this pattern in Yui used very much, the improvement is written:
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.

(6) code can be configured
The code you write needs to be configurable if you want to make it easier for others to use or modify, and the solution is to add a configuration object to the script you're writing. The main points are as follows:
1. Add a new 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, return this object as a public property so that others can rewrite 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.

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.