1. Simplify the code
It is very simple to define objects and arrays in JavaScript. We want to create an object, which is usually written like this:
var car = new Object();
car.colour = 'red' ;
car.wheels = 4;
car.hubcaps = 'spinning';
car.age = 4;
The following writing The same effect can be achieved:
var car = {
colour:'red',
wheels:4,
hubcaps:'spinning',
age:4
}
The following is much shorter, and you don’t need to write the object name repeatedly.
In addition, there is also a concise way to write arrays. In the past, we declared arrays as follows:
var moviesThatNeedBetterWriters = new Array(
'Transformers','Transformers2','Avatar','Indiana Jones 4 '
);
A more concise way of writing is:
var moviesThatNeedBetterWriters = [
'Transformers','Transformers2','Avatar ','Indiana Jones 4'
];
For arrays, there is a special thing like associative arrays. You will find that a lot of code defines objects like this:
< ;SPAN style="FONT-FAMILY: verdana, geneva">var car = new Array();
car['colour'] = 'red';
car['wheels'] = 4;
car['hubcaps'] = 'spinning';
car['age'] = 4;
This is crazy, don't get confused , "Associative array" is just an alias for an object.
Another way to simplify the code is to use the ternary operator, for example:
var direction;
if(x < 200){
direction = 1;
} else {
direction = -1;
}
We can use the following code to replace this writing:
var direction = x < ; 200 ? 1 : -1;
2. Using JSON as data format
The great Douglas Crockford invented the JSON data format to store data, you can Use native javascript methods to store complex data without any additional conversion, for example:
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 used in many APIs , for example:
<script> <br>function delicious(o){ <br>var out = '<ul>'; <br>for(var i=0;i<o.length;i ){ <BR>out = '<li><a href="' o [i].u '">' <br>o[i].d '</a></li>'; <br>} <br>out = '</ul>'; <br>document.getElementById('delicious').innerHTML = out; <br>} <br></script>
Here, call delicious's web service to get the latest bookmarks, return it in JSON format, and then Display them as an unordered list.
Essentially, JSON is the most lightweight way for describing complex data, and it runs directly in the browser. You can even use it by calling the json_decode() function in PHP.
3. Try to use JavaScript native functions
To find the maximum number in a set of numbers, we may write a loop, for example:
var numbers = [3,342,23,22,124];
var max = 0;
for(var i=0;iif(numbers[i] > max){
max = numbers[i];
}
}
alert(max);
In fact, the same function can be achieved without looping:
var numbers = [3,342 ,23,22,124];
numbers.sort(function(a,b){return b - a});
alert(numbers[0]);
The most concise way to write it is:
Math.max(12,123,3,2,433,4); // returns 433
You can even use Math.max to detect which attributes are supported by the browser:
var scrollTop= Math.max(
doc.documentElement.scrollTop,
doc.body.scrollTop
);
If you want to add a class style to an element, the original writing may be like this:
function addclass(elm,newclass){
var c = elm.className;
elm.className = (c === '') ? newclass : c ' ' newclass;
}
while A more elegant way of writing is:
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 click events to links in a list. The general approach is to write a loop and bind events to each link object. The HTML 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// Attach a listener to each link
links[i].addEventListener('click',handler,false);
};
function handler(e){
var x = e.target; // Get the link that was clicked
alert(x);
e.preventDefault();
};
})();
更合理的写法是只给列表的父对象绑定事件,代码如下:
(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. 匿名函数
关于JavaScript的最头疼的事情之一是,它的变量没有特定的作用范围。 一般情况下,任何变量,函数,数组或对象都是全局性,这意味着在同一页上的其他脚本可以访问并覆盖它们。解决方法是把变量封装在一个匿名函数中。 例如,下面的定义将产生三个全局变量和和两个全局函数:
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
封装后如下:
var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single';
return{
createMember:function(){
// [...]
},
getMemberDetails:function(){
// [...]
}
}
}();
// myApplication.createMember() and
// myApplication.getMemberDetails() now works.
这被称为单体模式,是JavaScript设计模式的一种,这种模式在YUI中用得非常多,改进的写法是:
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 configurability
If you want the code you write to be easier for others to use or modify, it needs to be configurable. The solution is to add a configuration object to the script you write. The key points are as follows:
1. Add an object called configuration in your script.
2. Store in the configuration object all the things that others may want to change, such as CSS ID, class name, language, etc.
3. Return this object as a public property so that others can override it.
7. Code Compatibility
Compatibility is a part that beginners tend to overlook. Usually when learning Javascript, it is tested in a fixed browser, and this browser is most likely IE. This It is very fatal, because among the major current browsers, IE has the worst support for standards. The result seen by the end user may be that the code you wrote cannot run correctly in a certain browser. You should test your code in all major browsers. This may be time-consuming, but it should be done.