The success of JavaScript is widely talked about. Writing JavaScript code for Web pages has become a basic skill for all Web designers. This interesting language contains many unknown things that even JavaScript programmers with many years of experience have not fully understood. . This article talks about those techniques in JavaScript that you are not very familiar with but are very practical from 7 aspects.
Abbreviated Statements
JavaScript can use abbreviated statements to quickly create objects and arrays, such as the following code:
var car = new Object();
car.colour = 'red';
car.wheels = 4;
car .hubcaps = 'spinning';
car.age = 4;
You can use abbreviated statements as follows:
var car = {
colour:'red',
wheels:4,
hubcaps:'spinning',
age:4
}
The object car is created, but special attention needs to be paid. Be sure not to add ";" before the closing curly brace, otherwise you will encounter big trouble in IE.
The traditional way to create an array is:
var moviesThatNeedBetterWriters = new Array(
'Transformers','Transformers2','Avatar','Indiana Jones 4'
);
Use abbreviated statements:
var moviesThatNeedBetterWriters = [
'Transformers','Transformers2',' Avatar','Indiana Jones 4'
];
Another question about arrays is whether there is such a thing as an associative array. You will find a lot of code examples defining the above car like this example
var car = new Array();
car['colour'] = 'red';
car['wheels'] = 4;
car['hubcaps'] = 'spinning' ;
car['age'] = 4;
Another place where abbreviated statements can be used is conditional statements:
var direction;
if(x < 200){
direction = 1;
} else {
direction = -1;
}
can be shortened to:
var direction = x < 200 ? 1 : -1;
JSON data format
JSON is the abbreviation of "JavaScript Object Notation" , designed by Douglas Crockford, JSON changes JavaScript's dilemma in caching complex data formats, as in the following example, if you want to describe a band, you can write like this:
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, even as the return data object of some APIs. The following code calls an API of the famous bookmark website delicious.com and returns the All bookmarks of this website and display them on your own website:
<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>
JavaScript native functions (Math, Array and String)
JavaScript has many built-in functions, which can be used effectively to avoid a lot of unnecessary code, for example, from an array To find the maximum value, the traditional method is:
var numbers = [3,342,23,22,124];
var max = 0;
for(var i=0;iif(numbers[i] > max){
max = numbers[i];
}
}
alert(max);
This is easier to achieve using built-in functions:
var numbers = [3,342,23,22,124];
numbers.sort(function (a,b){return b - a});
alert(numbers[0]);
Another method is to use the Math.max() method:
Math.max(12,123,3,2,433,4); // returns 433
You can use this method to help detect the browser
var scrollTop= Math.max(
doc.documentElement.scrollTop,
doc.body.scrollTop
);
This solves the problem of IE browser One problem is that with this method, you can always find the correct value, because the value that the browser does not support will return undefined.
You can also use JavaScript’s built-in split() and join() functions to process the CSS class name of the HTML object. If the class name of the HTML object is multiple names separated by spaces, you are appending or deleting a CSS class for it. Special attention should be paid to the name. If the object does not have a class name attribute, you can directly assign the new class name to it. If a class name already exists, there must be a space in front of the new class name. This is how it is implemented using the traditional JavaScript method. of:
function addclass(elm,newclass){
var c = elm.className;
elm.className = (c === '') ? newclass : c ' ' newclass;
}
Use split and join method rules Much more intuitive and elegant:
function addclass(elm,newclass) {
var classes = elm.className.split(' ');
classes.push(newclass);
elm.className = classes.join(' ');
}
Event proxy
Instead of designing a bunch of events in the HTML document, it is better to design an event proxy directly. For example, if you have some links, the user does not want to open the link after clicking it, but executes an event. The HTML code is as follows:
Traditional event processing is to traverse each link and add its own event processing:
// 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();
};
})();
Using event proxy, it can be processed directly without traversal:
(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();
}
};
}) ();
Anonymous functions and Module mode
A problem with JavaScript is that any variable, function or object, unless it is defined inside a function, is global, meaning Other code on the same page can access and overwrite this variable (ECMA's JavaScript 5 has changed this situation - Translator), using anonymous functions, you can bypass this problem.
For example, if you have a piece of code like this, obviously the variables name, age, status will become global variables
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
To avoid this problem, you can Use anonymous functions:
var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
}();
If this function will not be called, it can be more direct Copy the code for:
(function(){
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
})();
If you want to access the objects or functions inside, you can:
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 the so-called Module pattern or Singleton pattern, which is recommended by Douglas Crockford and widely used in Yahoo User Interface Library YUI.
If you want to call the methods inside elsewhere, but don’t want to use the object name myApplication before the call, you can return these methods in an anonymous function, or even return them with abbreviations:
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.
Code Configuration
When others use the JavaScript code you wrote, it is inevitable that they will change some of the code, but this will be difficult because not everyone is good at it. It is easier to read other people's code. Instead of doing this, it is better to create a code configuration object. Others only need to change certain configurations in this object to achieve code changes. Here is an article
detailed explanation of JavaScript configuration objects. In short:
· Create an object called configuration in code
· It saves all configurations that can be changed, such as CSS ID and class name, button label text, descriptive text, and localized language settings
·Set the object as a global object so that others can directly access and modify it
You should do this as the last step, here is an article, 5 things to do before shipping code for a valuable reference.
Interaction with the backend
JavaScript is a front-end language. You need other languages to interact with the backend and return data. Using AJAX, you can let JavaScript directly interact with the backend and hand over complex data processing. Processed by the background.
JavaScript Framework
Writing your own code to adapt to various browsers is a complete waste of time. You should choose a JavaScript framework and let the framework handle these complex things.
More resources
· Douglas Crockford on JavaScript
JavaScript in-depth video tutorial
· The Opera Web Standards Curriculum
JavaScript Detailed Explanation
Extended reading
· 10 puzzling things about JavaScript
· New API seeks to let JavaScript operate on local files
· Let JavaScript save HTML5 offline storage
· Open source projects are increasingly favoring JavaScript
· Is Javascript a bug?
· The future of Javascript 2 is settled
· 10 Most Famous JavaScript Libraries Ranked by Google
· ECMA launches JavaScript 5
International source of this article: Smashing Magazine Seven JavaScript Things I Wish I Knew Much Earlier In My Career (Original author: Christian Heilmann)