Home > Web Front-end > JS Tutorial > body text

Seven details of writing and development dedicated to JavaScript beginners_javascript skills

WBOY
Release: 2016-05-16 18:12:10
Original
1137 people have browsed it
(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:
Copy the code The code is 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 The code is as follows:

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 like this:
Copy code The code is as follows:

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

A more concise way of writing is:
Copy the code The code is as follows:

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:
Copy the code The code is as follows:

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:
Copy the code The code is as follows:

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

We can use the following code to replace this writing:
Copy the code The code is as follows:

var direction = x < 200 ? 1 : -1;

(2) Use JSON as 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 conversion, for example:

Copy code The 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 API. This is called JSON-P, which is used in many APIs. For example:
Copy code The code is as follows:

<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>
< script src="http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious">

Here, we call delicious’s web service to get the latest bookmarks, return them 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:
Copy code The code is as follows:

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:
Copy code The code is as follows:

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

The simplest way to write it is:
Copy code The code is as follows:

Math.max(12,123,3,2,433,4); // returns 433

You can even use Math.max to detect which properties the browser supports:
Copy code The code is 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 writing may be like this:
Copy code The code is as follows:

function addclass(elm,newclass){
var c = elm.className;
elm.className = (c === '') ? newclass : c ' ' newclass;

And a more elegant way of writing is:
Copy code The code is as follows:

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:
Copy Code The code is as follows:

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

A more reasonable way to write is to only bind events to the parent object of the list. The reason why this works is that events support bubbling. The code is as follows:
Copy code The code is 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 functions
One of the most annoying things about JavaScript is that its variables have no specific scope. In general, any variable, function, array or object is global, which means other scripts on the same page can access and overwrite them. The solution is to encapsulate the variable in an anonymous function. For example, the following definition will produce three global variables and two global functions:
Copy code The code is as follows:

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

After encapsulation, it is as follows:
Copy code The code is 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 singleton mode, which is a type of JavaScript design pattern. This mode is used a lot in YUI. The improved writing is:
Copy code The code is 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 configurable

If you want to make it easier for others to use the code you write, or To 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 go to a fixed browser This browser is most likely to be IE, which is very fatal, because among the current major mainstream 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.
Original text from: Seven JavaScript Things I Wish I Knew Much Earlier In My Career)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!