I've been writing JavaScript code for a long time, and I can't remember what era it started. I am very excited about what JavaScript has achieved in recent years, and I am fortunate to have benefited from these achievements. I've written a lot of articles, chapters, and a book devoted to it, but I can still find some new knowledge about the language. The following description is the past that I could not help but send out "Ah!" "The exclamation of programming skills, these tips you should try now, instead of waiting for some time in the future to find them by chance.
Concise notation
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 needed this:
1 var car = new Object();
2 car.colour = ‘red‘;
3 car.wheels = 4;
4 car.hubcaps = ‘spinning‘;
5 car.age = 4;
The following writing can achieve the same effect:
1 var car = {
2 colour:‘red‘,
3 wheels:4,
4 hubcaps:‘spinning‘,
5 age:4
6 }
It's much simpler, you don't have to use the name of the object repeatedly. So car is defined, perhaps you will encounter invaliduserinsession problem, this only you will encounter when using IE, just remember a little, do not put a comma in front of the curly braces, you will not have trouble.
Another very handy shorthand is for arrays. The traditional way to define arrays is this:
1 var moviesThatNeedBetterWriters = new Array(
2 ‘Transformers‘,‘Transformers2‘,‘Avatar‘,‘IndianaJones 4‘
3 );
The abbreviated version is this:
1 var moviesThatNeedBetterWriters = [
2 ‘Transformers‘,‘Transformers2‘,‘Avatar‘,‘IndianaJones 4‘
3 ];
For arrays, there is a problem here, in fact, there is no graph group function. But you'll often find that someone defines the car above, like this.
1 var car = new Array();
2 car[‘colour‘] = ‘red‘;
3 car[‘wheels‘] = 4;
4 car[‘hubcaps‘] = ‘spinning‘;
5 car[‘age‘] = 4;
arrays are not omnipotent; it is confusing to write them wrong. The graph group is actually the function of the object, and people confuse the two concepts.
Another very cool shorthand method is to use with ternary conditional notation. You don't have to write the following.
1 var direction;
2 if(x < 200){
3 direction = 1;
4 } else {
5 direction = -1;
6 }
...
You can use the ternary conditional notation to simplify it:
1 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 form
Before I found JSON, I used a variety of crazy methods to store data in JavaScript's intrinsic data types, such as arrays, strings, symbols that were easy to split, and other annoying things. After Douglas Crockford invented JSON, it all changed. Using JSON, you can use JavaScript's own functionality to store data in complex formats without the need for additional conversions that can be accessed directly. JSON is the abbreviation for "JavaScript Object Notation", which uses the two shorthand methods mentioned above. So, if you want to describe a band, you might write like this:
01 var band = {
02 "name":"The Red Hot Chili Peppers",
03 "members":[
04 {
05 "name":"Anthony Kiedis",
06 "role":"lead vocals"
07 },
08 {
09 "name":"Michael ‘Flea‘ Balzary",
10 "role":"bass guitar, trumpet, backing vocals"
11 },
12 {
13 "name":"Chad Smith",
14 "role":"drums,percussion"
15 },
16 {
17 "name":"John Frusciante",
18 "role":"Lead Guitar"
19 }
20 ],
21 "year":"2009"
22 }
You can use JSON directly in JavaScript to encapsulate it in a function, even as a return value for an API. We call this json-p, and many APIs use this form.
You can call a data supply source and return the JSON-P data directly in the script code:
01 <div id="delicious"></div><script>
02 function delicious(o){
03 var out = ‘<ul>‘;
04 for(var i=0;i<o.length;i++){
05 out += ‘<li><a href="‘ + o[i].u + ‘">‘ +
06 o[i].d + ‘</a></li>‘;
07 }
08 out += ‘</ul>‘;
09 document.getElementById(‘delicious‘).innerHTML = out;
10 }
11 </script>
12 <script src="http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious"></script>
This is the Web Service feature that is called by the Delicious Web site to get a list of the most recent unordered bookmarks in JSON format.
Basically, JSON is the lightest way to describe complex data structures, and it can be run in a browser. You can even run it in PHP with the Json_decode () function. One of the things that makes me wonder about JavaScript's own functions (math, Array, and string) is that when I look at math and string functions in JavaScript, I find that they can greatly simplify my programming work. Using them, you can eliminate complex cyclic processing and conditional judgments. For example, when I need to implement a function to find the largest number in a number array, I used to write this loop like this:
1 var numbers = [3,342,23,22,124];
2 var max = 0;
3 for(var i=0;i<numbers.length;i++){
4 if(numbers[i] > max){
5 max = numbers[i];
6 }
7 }
8 alert(max);
We can do this without the need for loops:
1 var numbers = [3,342,23,22,124];
2 numbers.sort(function(a,b){return b - a});
3 alert(numbers[0]);
It is important to note that you cannot sort () a numeric character array, because in this case it will only be sorted 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 number in the argument:
1 Math.max (12,123,3,2,433,4); Returns 433
Because this function can verify the number and return the largest one, you can use it to test the browser's support for a feature:
1 var scrollTop=Math.max(
2 doc.documentElement.scrollTop,
3 doc.body.scrollTop
4 );
This is used to solve the IE problem. You can get the scrolltop value of the current page, but depending on the DOCTYPE on the page, only one of these two properties will hold this value, and the other will be undefined, so you can get this number by using Math.max (). Reading this article will give you more knowledge about using mathematical functions to simplify JavaScript.
Another function that has a pair of very useful action strings is split () and join (). I think the most representative example would be to write a function that attaches a CSS style to the page element.
So, when you attach a CSS class to a page element, either it is the first CSS class of the element, or it already has some class, you need to add a space to the existing class, and then append the class. And when you want to get rid of this class, you also need to remove the space in front of this class (this is very important in the past, because some old browsers do not know the class that followed the space).
So, the original wording would be this:
1 function addclass(elm,newclass){
2 var c = elm.className;
3 elm.className = (c === ‘‘) ? newclass : c+‘ ‘+newclass;
4 }
You can use the split () and join () functions to automate this task:
1 function addclass(elm,newclass){
2 var classes = elm.className.split(‘ ‘);
3 classes.push(newclass);
4 elm.className = classes.join(‘ ‘);
5 }
This will ensure that all classes are separated by spaces, and that the class you want to append is exactly the last one.
Event delegation
Web applications are event-driven. I like event handling, and I especially like defining events myself. It allows you to expand your product without having to change the core code. There is a big problem (and it can be said to be a powerful performance) about the removal of events on the page. You can install an event listener on an element, and the event listener will begin to function. But there is no indication on the page that there is a listener. Because of this non-expressive problem (which in particular makes some novice headaches) and a "browser" like IE6, there are a variety of memory problems when listening to too many usage events, you have to admit that using event programming as little as possible is a smart idea.
Then the event delegation appeared.
When an event on an element on a page is triggered, and on the DOM inheritance, all child elements of the element can also receive this event, you can use an event handler on the parent element to process it instead of using an event listener on a bunch of individual child elements. What exactly does that mean? In this case, there are a lot of 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:
1 <h2>Great Web resources</h2>
2 <ul id="resources">
3 <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>
4 <li><a href="http://sitepoint.com">Sitepoint</a></li>
5 <li><a href="http://alistapart.com">A List Apart</a></li>
6 <li><a href="http://yuiblog.com">YUI Blog</a></li>
7 <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>
8 <li><a href="http://oddlyspecific.com">Oddly specific</a></li>
9 </ul>
A common practice is to loop through these links and attach an event handler to each link:
01 // Typical event processing example
02 (function () {
03 var resources = document.getElementById (‘resources’);
04 var links = resources.getElementsByTagName (‘a’);
05 var all = links.length;
06 for (var i = 0; i <all; i ++) {
07 // Attach a listener to each link
08 links [i] .addEventListener (‘click’, handler, false);
09};
10 function handler (e) {
11 var x = e.target; // Get the link that was clicked
12 alert (x);
13 e.preventDefault ();
14};
15)) ();
We can do this with an event handler:
01 (function(){
02 var resources = document.getElementById(‘resources‘);
03 resources.addEventListener(‘click‘,handler,false);
04 function handler(e){
05 var x = e.target; // get the link tha
06 if(x.nodeName.toLowerCase() === ‘a‘){
07 alert(‘Event delegation:‘ + x);
08 e.preventDefault();
09 }
10 };
11 })();
Because the click event occurs in these page elements, all you have to do is compare their nodeName to find out which element should respond to this event.
Disclaimer: The above two examples of events can be run in all browsers, except for IE6, on IE6 you need to use an event model, rather than a simple W3C standard implementation. That's why we recommend using some toolkits.
The benefit of this approach is not limited to reducing multiple event handlers to one. Think about it, for example, you need to dynamically add more links to this link list. After using event delegation, you don't need to make other changes; otherwise, you need to re-circulate the linked list and re-install the event handler for each link.
Anonymous functions and modularity
最 The most annoying thing in JavaScript is that variables have no scope. 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 can override it.
The solution is to put your variable inside an anonymous function and call it as soon as it is defined. For example, the following would produce three global variables and two global functions:
1 var name = ‘Chris‘;
2 var age = ‘34‘;
3 var status = ‘single‘;
4 function createMember(){
5 // [...]
6 }
7 function getMemberDetails(){
8 // [...]
9 }
If there is a variable called status in other scripts on this page, trouble will arise. If we encapsulate them in a myApplication, this problem is solved:
01 var myApplication = function(){
02 var name = ‘Chris‘;
03 var age = ‘34‘;
04 var status = ‘single‘;
05 function createMember(){
06 // [...]
07 }
08 function getMemberDetails(){
09 // [...]
10 }
11 }();
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:
01 (function(){
02 var name = ‘Chris‘;
03 var age = ‘34‘;
04 var status = ‘single‘;
05 function createMember(){
06 // [...]
07 }
08 function getMemberDetails(){
09 // [...]
10 }
11 })();
If you want to be able to use things inside the function, you need to modify it. In order to access createMember () or getMemberDetails (), you need to turn them into properties of myApplication and expose them to the outside world:
01 var myApplication = function () {
02 var name = ‘Chris’;
03 var age = ‘34’;
04 var status = ‘single’;
05 return {
06 createMember: function () {
07 // [...]
08},
09 getMemberDetails: function () {
10 // [...]
11}
12}
13) ();
14 //myApplication.createMember () and
15 //myApplication.getMemberDetails () is ready to use.
This is called the module pattern or singleton. Douglas Crockford talked about this many times, and there is a lot of use in the Yahoo User Interface Library YUI. But what made me feel inconvenient was that I needed to change the syntax to make functions and variables accessible to the outside world. What's more, I need to prefix myApplication when calling. Therefore, I don't like to do this, I prefer to simply export pointers to elements that need to be accessible from the outside world. After doing so, it simplifies the writing of external calls instead:
01 var myApplication = function () {
02 var name = ‘Chris’;
03 var age = ‘34’;
04 var status = ‘single’;
05 function createMember () {
06 // [...]
07}
08 function getMemberDetails () {
09 // [...]
10}
11 return {
12 create: createMember,
13 get: getMemberDetails
14}
15) ();
16 // Now write myApplication.get () and myApplication.create ().
I call this "revealing module pattern."
Configurable
Once I publish the JavaScript code I write into this world, there are people who want to change it. Usually people want it to accomplish some tasks that they can't do by themselves-but usually the programs I write are not flexible enough to provide users with the Defined features. The solution is to add a configuration item object to your script. I have written an article that introduces JavaScript configuration item objects in depth, here are the main points:
Add an object called configuration to your script.
This object stores all the things that people often change when using this script:
CSS ID and class name;
The name of the button, the label word, etc .;
Values such as "the number of pictures displayed per page", "the displayed size of an image";
Location, location, and language settings.
This object is returned to the user as a public property so that the user can modify and override it.
Usually this is the last step in your programming process. I put these together in an example: "Five things to do to a script before handing it over to the next developer."
In fact, you also hope that your code can be used by people in many ways, and make some changes according to their respective needs. If you implement this feature, you will receive fewer confusing emails from people complaining about your script. These letters will tell you that someone has modified your script and it works well.
交互 Interact with the background
这么 In all these years of programming experience, an important thing I have learned is that JavaScript is a very good language for developing interface interactions, but if it is used to process numbers or access data sources, it will be a bit unbearable.
In the beginning, I learned JavaScript and used it instead of Perl, because I hated having to copy the code to the cgi-bin folder to make Perl run. Later, I realized that I should use a language that works in the background to process the main data, and not let everything be done by JavaScript. More importantly, we need to consider security and language features.
If I access a Web service, I can get the data in JSON-P format. In the client browser, I do all kinds of data conversion, but when I have the server, I have more Method to convert data, I can generate JSON or HTML format data on the server side and return it to the client, and cache data. If you know and prepare these beforehand, you will gain long-term benefits and save a lot of headache time. Writing programs for all browsers is a waste of time, use the toolkit!
我 When I first started web development, when I visited the page, I had to struggle with document.all or document.layers. 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. When Netscape 6 announced that it only supported the W3C DOM model, I was happy, but users didn't really care about it. Users just see that this kind of browser can't display what most browsers can display normally-this is a coding problem. We wrote short-sighted code that can only run in the current environment, but 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 dealing with such problems 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 such problems. They deal with the various problems of the browser by abstracting the implementation of various interfaces, such as incompatible versions, design flaws, etc., which save us from pain. Unless you want to test a Beta browser, don't add code to fix the browser's defects in your program, because you most likely have forgotten to delete your browser The code.
On the other hand, relying entirely on the toolkit is also short-sighted. Toolkits can help you develop quickly, but if you don't understand JavaScript in depth, you can also do wrong.
7 JavaScript Tips You Should Know