9 Pitfalls of error profiling JavaScript and comment _javascript skills

Source: Internet
Author: User
From nine JavaScript gotchas, here are nine pitfalls that JavaScript can easily make mistakes. Although not a very sophisticated technical problem, but note that will make your programming easier, that is, the so-called making life easier. Some of the traps will be mixed with some commentary.

1, the last comma
As with this code, note the last comma, which should be a good linguistic point (as Python's Dictionary of Data Type Dictionary allows). IE will report grammatical errors, but vague, you can only employ eyes from thousands of lines of code scan.

<script> var theobj = {city: ' Boston ', State: ' MA ',} </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]


2, the reference to this will change
such as this code:
<input type= "button" value= "gotcha!" id= "MyButton" > <script> var MyObject = function () {This.alert message = "Javascript rules"; This. ClickHandler = function () {alert (this.alertmessage); } }(); document.getElementById ("TheText"). onclick = Myobject.clickhandler </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]


Not as you would like, the answer is not "JavaScript rules." When the Myobject.clickhandler is executed, the red line in the code, where the reference to this actually points to a reference to document.getElementById ("TheText"). Can solve this:
<input type= "button" value= "gotcha!" id= "thetext" > <script> var MyObject = function () {var self = This This.alertmessage = "Javascript rules"; This. OnClick = function () {alert (self.value); } }(); document.getElementById ("TheText"). onclick = Myobject.onclick </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Essentially, that's the problem with JavaScript scopes. If you've seen it, you'll find more than one solution.

3. Identify thieves
Do not use the same variable names as HTML IDs in JavaScript. The following code:


<input type= "button" id= "Thebutton" > <script> Thebutton = Get ("Thebutton"); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

IE will report an undefined error to the object. I can only say: IE sucks.

4, the string only replaces the first match
The following code:


<script> var fileName = "This is a title". Replace ("", "_"); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

In fact, the result is "this_is a title". In JavaScript, the first argument for String.Replace should be a regular expression. So the right thing to do is to:


var fileName = "This is a title". Replace (//g, "_");


5. Mouseout sometimes means mousein.
In fact, this is caused by event bubbling. There are MouseEnter and mouseleave in IE, but not standard. The author recommends that you use the library such as Yui to solve the problem.

6, Parseint is based on the system of
This is common sense, but a lot of people ignore the parseint also has a second parameter to indicate the system. For example, parseint ("09"), if you think the answer is 9, that's wrong. Because, here, the string starts with a 0, parseint octal to handle it, in octal, 09 is illegal, returns false, and the Boolean value false converts to a value of 0. Therefore, the correct approach is parseint ("09", 10).

7, for...in ... Will traverse all the things
There is a piece of code like this:


var arr = [5,10,15]
var total = 1;
for (var x in arr) {
Total = total * Arr[x];
}

It's a good run, isn't it? But one day it was gone, and the value returned to me became Nan, dizzy. I just introduced a library. The original is this library rewrite the array of prototype, so that our arr no more than a property (method), and for...in ... Will pass it through. So it's safer to do this:


for (var x = 0; x < Arr.length + +) {
Total = total * Arr[x];
}

In fact, this is the pollution of the basic categories of prototype can bring harm to an example.

8, the event processor trap
This actually only exists if you use an event handler that is an object property. such as Window.onclick = Myonclickmethod Such code, this will duplicate the previous Window.onclick event, but also may cause IE content leakage (sucks again). Before IE has not supported the DOM 2 event registration, the author recommends using a library to solve the problem, such as using Yui:


YAHOO.util.Event.addListener (Window, "click", Myonclickmethod);

This should also be a common sense problem, but beginners may easily make mistakes.

9, Focus Pocus
Create a new input text element and then move the focus to it, which logically should be natural:


var newinput = document.createelement ("input");
Document.body.appendChild (Newinput);
Newinput.focus ();
Newinput.select ();

But IE will make an error (sucks again and again). The reason may be that when you perform focus (), the element does not exist yet. Therefore, we can defer execution:


var newinput = document.createelement ("input");
Newinput.id = "Thenewinput";
Document.body.appendChild (Newinput);
settimeout (function () {//Here I rewrite it with a closure, if interested can compare the original
document.getElementById (' Thenewinput '). focus ();
document.getElementById (' Thenewinput '). Select ();}, 10;

In practice, JavaScript traps still have a lot of, mostly because the implementation of the parser is not in place and caused. These things are not usually found in textbooks, and can only be shared by the experience of developers. Thank goodness, we live in the internet age, many problems encountered, generally can find the answer in Google.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.