


Detailed introduction to seven details that JavaScript beginners should pay attention to_Basic knowledge
May 16, 2016 pm 05:45 PMEach language has its own special features. For JavaScript, you can use var to declare variables of any type. This scripting language seems very simple, but writing elegant code requires continuous accumulation of experience. This article lists seven details that JavaScript beginners should pay attention to and share them with you.
(1) Simplify the code
--------------------------------- -----------------------------------------------
JavaScript is very simple to define objects and arrays. We want to create an object, usually written like this:
var car = new Object();
car.colour = 'red';
car.wheels = 4;
car.hubcaps = 'spinning';
car.age = 4;
The following writing can achieve the same effect:
var car = {
colour:'red',
wheels:4,
hubcaps:'spinning',
age:4
}
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'
);
More The concise way to write it 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:
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) Use JSON as data format
Invented by the great Douglas Crockford 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 API, which is used in many APIs, such as:
<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> ;
Here calls delicious's web service to get the latest bookmarks, returns them in JSON format, and then displays them in 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 might write a loop, for example:
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);
Actually, no need Loops can achieve the same function:
var numbers = [3,342 ,23,22,124];
numbers.sort(function(a,b){return b - a});
alert(numbers[0]);
And the most concise The writing method is:
Math.max(12,123,3, 2,433,4); // returns 433
You can even use Math.max to detect which properties the browser supports:
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;
The more elegant way of writing is:
function addclass(elm,newclass){
var classes = elm.className.split(' ');
classes.push(newclass);
elm.className = classes.join(' ');
}
(4) Event delegate
-------------- -------------------------------------------------- ----------------
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:
<h2>Great Web resources</h2>
<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>
脚本如下:
// 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 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 configurable
-------------------------------- ---------------------------------------------
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, they are tested in a fixed browser, and this browser is most likely IE. This is very fatal, because there are currently several major mainstream browsers. Among 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.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Become a C expert: Five must-have compilers recommended

C++ or Python, which one is more suitable for beginners?

WooCommerce Tax Guide: A Guide for Beginners

Python beginners must learn: Master the basic usage of lambda functions

Pandas Beginner's Guide: HTML Table Data Reading Tips

A must-read for beginners: How to choose the appropriate Django version according to your needs?

Should programming beginners learn C language or C first?

A beginner's guide to making scatter plots with matplotlib
