I have been writing JavaScript code for a long time and can't remember what era it started. I am very excited about the achievements of JavaScript in recent years; I am very lucky to be the beneficiary of these achievements. I have written a lot of articles, chapters, and a book dedicated to it, but I can still find some new knowledge about this language now. The following describes programming skills that made me sigh "Ah!" in the past. You should try these skills now, rather than waiting to accidentally discover them some time in the future.
Concise writing
One of my favorite things in JavaScript is the abbreviation method of generating objects and arrays. In the past, if you wanted to create an object you would need to do 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:
var car = { colour:'red', wheels:4, hubcaps:'spinning', age:4 }It's much simpler, you don't need to use the name of this object repeatedly. In this way, car is defined. Maybe you will encounter the problem of invalidUserInSession, which is only encountered when you use IE. Just remember one thing and don’t write commas before the closing braces, and you won’t have any trouble.
Another very convenient abbreviation is for arrays. The traditional way to define an array is as follows:
var moviesThatNeedBetterWriters = new Array( 'Transformers','Transformers2','Avatar','IndianaJones 4' );
The abbreviation version is like this:
var moviesThatNeedBetterWriters = [ 'Transformers','Transformers2','Avatar','IndianaJones 4' ];
For arrays, there is a problem here, but there is actually no graph group function. But you will often find that someone defines the above car like this, like this
var car = new Array(); car['colour'] = 'red'; car['wheels'] = 4; car['hubcaps'] = 'spinning'; car['age'] = 4;
Arrays are not omnipotent; if they are written incorrectly, they will be confusing. Graph groups are actually the function of objects, and people have confused these two concepts.
Another very cool abbreviation method is to use ternary conditional symbols. You don't have to write it as below...
var direction; if(x < 200){ direction = 1; } else { direction = -1; }…You can simplify it with ternary conditional notation:
var direction = x < 200 ? 1 : -1;
When the condition is true, the value after the question mark is taken, otherwise the value after the colon is taken.
Store data in JSON
Before I discovered JSON, I used various crazy methods to store data in JavaScript's inherent data types, such as arrays, strings, glyphs that are easy to split and other annoying things. After Douglas Crockford invented JSON, everything changed. Using JSON, you can use JavaScript's own functions to store data into complex formats, and there is no need to do other additional conversions, and you can directly access it. JSON is the abbreviation of "JavaScript Object Notation", which uses the two abbreviation methods mentioned above. So, if you want to describe a band, you might 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, encapsulate it in functions, or even use it as a return value form of an API. We call this JSON-P, and many APIs use this form.
You can call a data supply source and directly return JSON-P data in script code:
<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>This calls the Web service feature provided by the Delicious website to get the most recent unordered bookmark list in JSON format.
Basically, JSON is the lightest way to describe complex data structures, and it can run in the browser. You can even run it in PHP with the json_decode() function. One thing that surprised me about JavaScript's own 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 judgments. For example, when I need to implement a function to find the largest number in the number array, I used to write this loop like this:
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);We can do it without looping:
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 sort in alphabetical order. If you want to know more about the usage, you can read this good article about sort().
Another interesting function is Math.max(). This function returns the largest number in the parameter:
Math.max(12,123,3,2,433,4); // returns 433
Because this function can verify numbers and return the largest one, you can use it to test the browser's support for a feature:
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 number by using Math.max(). Read this article and you will get more knowledge about using mathematical functions to simplify JavaScript.
There are also a pair of very useful functions that operate strings are split() and join(). I think the most representative example would be to write a function to attach CSS style to page elements.
It's like this. When you append a CSS class to the page element, either it is the first CSS class of this element, or it already has some classes. You need to add a space after the existing class and then follow this class. And when you want to remove this class, you also need to remove the spaces in front of this class (this was very important in the past because some old browsers did not recognize the class followed by the spaces).
So, the original writing will look like this:
function addclass(elm,newclass){ var c = elm.className; elm.className = (c === '') ? newclass : c+' '+newclass; }You can use split() and join() functions to automatically complete 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 that the class you want to append is placed exactly the last one.
Event delegation
Web applications are all driven by event. I like event handling, especially I like to define events myself. It makes your product scalable without changing the core code. There is a big problem (also a powerful manifestation) about the removal of events on the page. You can install an event listener on an element and the event listener starts to work. But there is no indication on the page that there is a listener. Because of this unpredictable problem (which is particularly troublesome for some newbies), and the various memory problems that "browsers" like IE6 use too many event listening, you have to admit that it is wise to try to use event programming as little as possible.
So the commission of the incident occurred.
When an event on an element on the page is triggered, and in the DOM inheritance relationship, all children of this element can also receive this event. At this time, you can use an event handler on the parent element to handle it, rather than using event listeners on a bunch of child elements to handle it. 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:
<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>
It is a common practice to loop through these links and attach an event handler to each link:
// Typical 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(); }; })();We can also accomplish this task with an event processor:
(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(); } }; })();Because the click event occurs in these page elements, all you have to do is compare their nodeNames and find out which element should respond to the event.
Disclaimer: The two examples about events mentioned above can run in all browsers. Except for IE6, you need to use an event model on IE6, rather than a simple W3C standard implementation. This is why we recommend using some toolkits.
The benefit of this approach is not limited to reducing multiple event processors 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 re-loop this link table and install the event handler for each link again.
Anonymous functions and modularity
The most annoying thing in JavaScript is that variables have no scope to use. Any variable, function, array, object, as long as it is not inside the function, is considered global, which means that other scripts on this page can also access it and override it.
The solution is to put your variable inside an anonymous function and call it immediately after it is defined. For example, the following writing method will produce three global variables and two global functions:
var name = 'Chris'; var age = '34'; var status = 'single'; function createMember(){ // [...] } function getMemberDetails(){ // [...] }If there is a variable called status in other scripts on this page, trouble will occur. If we encapsulate them in a myApplication, this problem will be solved:
var myApplication = function(){ var name = 'Chris'; var age = '34'; var status = 'single'; function createMember(){ // [...] } function getMemberDetails(){ // [...] } }();However, this way, there is no function outside the function. If this is what you need, that's fine. You can also omit the name of the function:
(function(){ var name = 'Chris'; var age = '34'; var status = 'single'; function createMember(){ // [...] } function getMemberDetails(){ // [...] } })();If you want to use the inside of the function, you need to make some modifications. In order to access createMember() or getMemberDetails(), you need to turn them into myApplication properties to expose them to the external world:
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.This is called module mode or singleton. Douglas Crockford has talked about this many times, and it is widely used in the Yahoo User Interface Library YUI. But what makes me inconvenient is that I need to change the sentence structure so that functions and variables can be accessed by the outside world. What's more, I need to add the prefix of myApplication when calling. So, I don't like to do this, I prefer to simply export pointers to elements that need to be accessed by the outside world. After doing this, the writing of external calls is simplified:
var myApplication = function(){ var name = 'Chris'; var age = '34'; var status = 'single'; function createMember(){ // [...] } function getMemberDetails(){ // [...] } return{ create:createMember, get:getMemberDetails } }(); // Now write it as myApplication.get() and myApplication.create().I call this "revealing module pattern."
Configurable
Once I published the JavaScript code I wrote to this world, someone wanted to change it, usually people wanted to complete tasks that it could not complete itself - but usually the program I wrote was not flexible enough and did not provide user-defined functions. The solution is to add a configuration item object to your script. I once wrote an article that introduces JavaScript configuration item objects in depth. Here are the key points:
----In your script, add an object called configuration.
----This object stores all things that people often need to change when using this script:
**CSS ID and class name;
** button name, label word, etc.;
** Values such as "number of pictures displayed per page" and "size of images displayed";
** Location, location, and language settings.
---Return this object to the user as a common property so that the user can modify and overwrite it.
This is usually what you need to do in the last step in your programming process. I concentrated these in one example: “Five things to do to a script before handing it over to the next developer.”
In fact, you also want your code to be used in a very good way and make some changes according to their respective needs. If you implement this feature, you will receive less confusing emails from people who complain about your script, which will tell you that someone has modified your script and it is very useful.
Interact with the background
One of the important things I have learned in so many years of programming experience is that JavaScript is an excellent language for developing interface interaction, but if it is used to process numbers or access data sources, it is a bit unsatisfactory.
Initially, I learned JavaScript to replace Perl because I hate having to copy the code to the cgi-bin folder to make Perl run. Later, I realized that I should use a backend working language to process the main data, and I cannot let JavaScript do everything. More importantly, we need to consider security and language characteristics.
If I access a Web service, I can get the data in JSON-P format. In the client browser, I do various data conversion, but when I have a server, I have more ways to convert the data. I can generate JSON or HTML format data on the server side and return it to the client, as well as cache data, etc. If you understand and prepare these in advance, you will make long-term gains and save a lot of headaches. Writing programs that are suitable for various browsers is a waste of time, use the toolkit!
When I first started web development, I struggled hard for a long time on whether to use document.all or document.layers when accessing the page. I chose document.layers because I like the idea that any layer is its own document (and I wrote too many document.write to generate elements). The layer pattern eventually failed, so I started using document.all. I was very happy when Netscape 6 announced that it only supports W3C DOM models, but in fact users didn't care about this. Users just see that such browsers cannot display things that most browsers can display normally - this is a problem with our encoding. We wrote short-sighted code that can only be run in the current environment, but unfortunately, our operating environment is constantly changing.
I've been wasting too much time dealing with compatibility with various browsers and various versions. Being good at dealing with this kind of problem provides me with a good job opportunity. But now we don't have to endure this pain.
Some toolkits, such as YUI, jQuery and Dojo, can help us deal with this kind of problem. They solve various browser problems by abstracting various interface implementations, such as version incompatibility, design flaws, etc., which saves us from our pain. Unless you want to test a certain beta browser, don't add code to your own program to correct the browser's defects, because you are likely to forget to delete your code when the browser has modified this problem.
On the other hand, relying entirely on toolkits is also a short-sighted behavior. Toolkits can help you develop quickly, but if you don't have a deep understanding of JavaScript, you will also do something wrong.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.