Home > Web Front-end > JS Tutorial > 7 JavaScript tricks you should have known before_javascript tricks

7 JavaScript tricks you should have known before_javascript tricks

WBOY
Release: 2016-05-16 17:39:22
Original
1018 people have browsed it

I have been writing JavaScript code for so long that I can’t even remember when I started. I'm very excited about what JavaScript has accomplished in recent years; I've been lucky enough to be a beneficiary of these achievements. I've written quite a few articles, chapters, and a book dedicated to it, and yet I'm still discovering new things about the language. The following descriptions are programming techniques that have made me say "Ah!" in the past, and they are techniques you should try now rather than wait to stumble upon them sometime in the future.

Concise writing

One of my favorite things in JavaScript is the shorthand method for generating objects and arrays. In the past, if you wanted to create an object, you would go like this:

Copy the code The code would look like this:

var car = new Object();
car.colour = 'red';
car.wheels = 4;
car.hubcaps = 'spinning';
car.age = 4;

The following writing method can achieve the same effect:
Copy the code The code is as follows:

var car = {
colour:'red',
wheels:4,
hubcaps:'spinning',
age:4
}


Much simpler, you don’t need to use the name of the object repeatedly. In this way, car is defined. Maybe you will encounter the problem of invalidUserInSession. This will only happen when you use IE. Just remember one thing, do not write a comma in front of the closing brace, and you will not have trouble.

Another very convenient abbreviation is for arrays. The traditional way to define an array is as follows:

Copy the code The code is as follows:

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

The abbreviated version is like this:
Copy code The code is as follows:

var moviesThatNeedBetterWriters = [
'Transformers','Transformers2' ,'Avatar','IndianaJones 4'
];

For arrays, there is a problem. In fact, there is no graph group function. But you will often find people defining the above car like this, 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;


Arrays are not omnipotent; if this is not written correctly, it will be confusing. Graph groups are actually functions of objects, and people confuse the two concepts.

Another very cool shorthand method is to use the ternary conditional notation. You don’t have to write it like this...

Copy the code The code is as follows:

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


you You can simplify it using the ternary conditional notation:

Copy the code The code is as follows:

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

When the condition is true, take the value after the question mark, otherwise take the value after the colon.

Storing data in JSON format

Before I discovered JSON, I used all kinds of crazy methods to store data in JavaScript’s native data types, such as arrays, strings, mixed with easy-to-split symbols and other confusing Nasty stuff. Everything changed when Douglas Crockford invented JSON. Using JSON, you can use JavaScript's own functions to store data into complex formats, and it can be directly accessed and used without any additional conversion. JSON is the abbreviation of "JavaScript Object Notation", which uses the two abbreviations mentioned above. So, if you wanted to describe a band, you might write it like this:

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, encapsulate it in a function, or even use it as the return value of an API. We call this JSON-P, and many APIs use this format.

You can call a data provider and return JSON-P data directly in the script code:

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>



This is to call the Web service function provided by the Delicious website to obtain the recent unordered bookmark list in JSON format.

Basically, JSON is the most portable way to describe complex data structures, and it can run in the browser. You can even run it in PHP using the json_decode() function. One thing that surprised me about JavaScript's built-in functions (Math, Array and String) is that after I studied the math and String functions in JavaScript, I found that they can greatly simplify my programming work. Using them, you can save complex loop processing and conditional judgment. For example, when I needed to implement a function to find the largest number in an array of numbers, I used to write the loop like this:

Copy Code The code is as follows:

var numbers = [3,342,23,22,124];
var max = 0;
for(var i=0 ;i if(numbers[i] > max){
max = numbers[i];
}
}
alert(max);

We can achieve this 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 ]);

It should be noted that you cannot sort() an array of numeric characters, because in this case it will only be sorted in alphabetical order. If you want to know more usage, you can read this good article about sort().

Another interesting function is Math.max(). This function returns the largest number among the numbers in the parameter:

Copy code The code is as follows:

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

Because this function can check numbers and return the largest one, you can use it to test browsing The server's support for a certain feature:
Copy the code The code is as follows:

var scrollTop= Math.max(
doc.documentElement.scrollTop,
doc.body.scrollTop
);

This is used to solve IE problems. You can get the scrollTop value of the current page, but depending on the DOCTYPE on the page, only one of the above two properties will store this value, and the other property will be undefined, so you can get this by using Math.max() number. Read this article to learn more about using math functions to simplify JavaScript.

Another pair of very useful functions for manipulating strings are split() and join(). I think the most representative example is writing a function to attach CSS styles to page elements.

This is like this, when you attach a CSS class to a page element, it is either the first CSS class of this element, or it already has some classes, and you need to add a space after the existing classes. , and then append this class. And when you want to remove this class, you also need to remove the space in front of the class (this was very important in the past, because some old browsers did not recognize classes followed by spaces).

So, the original writing would be like this:

Copy the code The code is as follows:

function addclass(elm,newclass){
var c = elm.className;
elm.className = (c === '') ? newclass : c ' ' newclass;
}You can Use the split() and join() functions to automate this task:

function addclass(elm,newclass){
var classes = elm.className.split(' ');
classes.push(newclass);
elm.className = classes.join(' ' );
}



This will ensure that all classes are separated by spaces, and the class you want to append is placed at the end.

Event Delegation

Web applications are event-driven. I like event handling, especially defining events myself. It makes your product extensible without changing the core code. There is a big problem (and a powerful manifestation), regarding the removal of events on the page. You can install an event listener on an element and the event listener will start working. But there is no indication on the page that there is a listener. Because of this non-expressible problem (which is especially troublesome for some newbies), and the various memory problems that occur when "browsers" like IE6 use too many event listeners, you have to admit that you should use event programming as little as possible It's a wise move.

So event delegation appeared.

When an event on an element on the page is triggered, and in the DOM inheritance relationship, all child elements of this element can also receive this event. At this time, you can use an event handler on the parent element to Processing instead of using a bunch of event listeners on individual child elements. What exactly does it mean? Let’s put it this way, there are many hyperlinks on the page. You don’t want to use these links directly. You want to call this link through a function. The HTML code is like this:

Copy code The code is as follows:


A common approach is to loop through these links and attach an event handler to each link:

Copy code The code is as follows:

// Typical event processing 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();
};
})( );

We can also accomplish this task using an event handler:
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:' Here, all you have to do is compare their nodeNames to find out which element should respond to this event.

Disclaimer: The two examples of events mentioned above can be run in all browsers, except IE6. On IE6, you need to use an event model instead of a simple W3C standard implementation. This is why we recommend using some tool kits.

The benefits of this approach are not limited to reducing multiple event handlers into one. Think about it, for example, you need to dynamically add more links to this link table. After using event delegation, you don't need to make any other changes; otherwise, you need to recycle the link list and reinstall the event handler for each link.

Anonymous functions and modularity

The most annoying thing in JavaScript is that variables don’t have scope. Any variable, function, array, or object that is not inside a function is considered global, which means that other scripts on this page can also access it and overwrite it.

The solution is to put your variable inside an anonymous function and call it immediately after defining it. For example, the following writing will generate three global variables and two global functions:

Copy the code


The code is as follows:

}
function getMemberDetails(){
// [...]
}


Trouble will arise if there is a variable called status in other scripts on this page. If we encapsulate them in a myApplication, this problem will be solved:
Copy code The code is as follows:

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

However, in this case, there is no function outside the function. If that's what you need, that's fine. You can also omit the name of the function:
Copy the code The code is as follows:

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

If you want to do it outside the function If you can use what's inside, you'll need to make some modifications. In order to access createMember() or getMemberDetails(), you need to expose them to the outside world by making them properties of myApplication:
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() can be used.
[code]
This is called module pattern or singleton. Douglas Crockford talks about this a lot, and the Yahoo User Interface Library YUI makes extensive use of it. But what makes me feel inconvenient is that I need to change the sentence structure to make the functions and variables accessible to the outside world. What's more, I need to add the prefix myApplication when calling. So, I don't like to do this, I prefer to simply export the pointers to the elements that need to be accessible to the outside world. After doing this, it simplifies the writing of external calls:
[code]
var myApplication = function(){
var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
// [...]
}
function getMemberDetails(){
// [...]
}
return{
create:createMember,
get:getMemberDetails
}
}();
//Now just write myApplication.get() and myApplication.create() . I call this “revealing module pattern.”


Configurable

As soon as I put the JavaScript code I write out into the world, someone wants to change it, usually people who want it to do something with it Tasks that cannot be accomplished by themselves—but often the programs I write are not flexible enough and do not provide user-customizable functionality. The solution is to add a configuration item object to your script. I once wrote an in-depth article introducing JavaScript configuration object objects. Here are the key points:

Add an object called configuration to your script.
In this object, all the things that people often change when using this script are stored:
CSS ID and class name;
Button name, label word, etc.;
Such as "display images on each page" Number" value, "Image display size" value;
Location, location, and language settings.
Return this object to the user as a public property so that the user can modify and overwrite it.
Normally this is the last step in your programming process. I summarized these in an example: "Five things to do to a script before handing it over to the next developer."

Actually, you also want your code to be useful to people. used, with some modifications to suit their respective needs. If you implement this feature, you'll receive fewer confusing emails from people complaining about your script, telling you that someone modified your script and it works great.

Interacting with the background

In so many years of programming experience, one important thing I have learned is that JavaScript is an excellent language for developing interface interactions, but if it is used Crunching numbers or accessing data sources is a bit of a drag.
Initially, I learned JavaScript to replace Perl, because I hated having to copy the code to the cgi-bin folder to make Perl run. Later, I understood that I should use a background work language to handle the main data, instead of letting JavaScript do everything. What's more important is that we have to consider security and language features.

If I access a Web service, I can get data in JSON-P format, and I do various data conversions on it in the client browser, but when I have a server, I have more ways to convert data. I can generate data in JSON or HTML format on the server side and return it to the client, as well as cache data and other operations. If you understand and prepare these beforehand, you will benefit in the long run and save yourself a lot of headaches. Writing programs that work across all browsers is a waste of time, use a toolkit!

When I first started to engage in web development, I struggled for a long time with the question of whether to use document.all or document.layers when accessing a page. I chose document.layers because I like the idea of ​​any layer being its own document (and I was writing too many document.writes to generate elements). Layers pattern eventually failed, so I started using document.all. I was happy when Netscape 6 announced support for the W3C DOM model only, but users didn't really care. The user just sees that this browser cannot display something that most browsers can display properly - it is a problem with our coding. We write short-sighted code that can only run in the current environment, and unfortunately, our operating environment is constantly changing.

I have wasted too much time dealing with compatibility issues with various browsers and versions. Being good at handling such problems provides me with a good job opportunity. But now we don't have to endure this pain anymore.

Some toolkits, such as YUI, jQuery and Dojo, can help us deal with this kind of problem. They deal with various browser problems by abstracting various interface implementations, such as version incompatibility, design defects, etc., saving us from pain. Unless you want to test a beta version of the browser, never add code to fix the browser's flaws in your program, because you are likely to forget to delete your code when the browser has fixed the problem. code.

On the other hand, relying solely on toolkits is also short-sighted. Toolkits can help you develop quickly, but if you don't understand JavaScript deeply, you can also do things wrong.
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