9 traps and comments of JavaScript

Source: Internet
Author: User

From nine JavaScript gotchas, the following are nine traps that JavaScript is prone to mistakes. Although it is not a very profound technical problem, please note that it will make your programming easier, that is, make life easier. I will give some comments on some traps.

  1. Last comma

    For exampleCodeNote that the last comma should be good in terms of Linguistics (this is allowed in Python's dictionary similar to data types ). Internet Explorer reports syntax errors, but it is not detailed. You can only scan thousands of lines of code.

    <SCRIPT>
    VaR theobj = {
    City: "Boston ",
    State: "Ma ",
    }
    </SCRIPT>
  2. This Will change

    Such as this Code:

     
    <Input type = "button" value = "Gotcha! "Id =" mybutton ">
    <SCRIPT>
    VaR myobject = function (){
    This. alertmessage = "javascript rules ";
    This. clickhandler = function (){
    Alert (this. alertmessage );} (); Document. getelementbyid ("thetext"). onclick = myobject. clickhandler </SCRIPT>

    The answer is not "javascript rules", as you wish ". In executionMyobject. clickhandlerThe red line in the code,ThisReferences actually pointDocument. getelementbyid ("thetext "). It can be solved as follows:

     
    <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>

    Essentially, this is the Javascript scope issue. If you see it, you will find that there are more than one solution.

  3. Identify thieves

    Do not use variable names with the same html id in JavaScript. The following code:

    <Input type = "button" id = "thebutton">
    <SCRIPT>
    Thebutton = get ("thebutton ");
    </SCRIPT>

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

  4. The string must replace the first match.

    The following code:

    <SCRIPT>
    VaR filename = "this is a title". Replace ("","_");
    </SCRIPT>

    In fact, the result is"This_is a title". In JavaScript,String. ReplaceThe first parameter must be a regular expression. Therefore, the correct method is as follows:

    VaR filename = "this is a title". Replace (// G ,"_");
  5. Mouseout means mousein

    In fact, this is caused by event bubbling. IE hasMouseenterAndMouseleaveBut not standard. The author suggests that you use library, such as Yui, to solve the problem.

  6. ParseintIs based on the hexadecimal System

    This is common sense, but many people ignore it.ParseintThe second parameter is used to indicate the hexadecimal notation. For example,Parseint ("09 ")If you think the answer is 9, it is wrong. Because, here, the string starts with 0,ParseintHandle it in octal mode. In octal mode,09Is invalid and returnsFalse, Boolean ValueFalseThe correct way to convert to a value is 0.Parseint ("09", 10).

  7. For... in...Will traverse all 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];
    }

    Running well, isn't it? But one day it quit, and the returned value is changedNan, Dizzy. I just introduced a library. It turns out that this library has been rewritten.ArrayOfPrototypeIn this way, ourArrThere is no more than one attribute (method ),For... in...It will be traversed. Therefore, this is safer:

    For (VAR x = 0; x <arr. length; X ++ ){
    Total = total * arr [x];
    }

    In fact, this is also a basic type of pollution.PrototypeAn example of the potential harm.

  8. Event processor traps

    In fact, only the event processor used as the object property will exist. For exampleWindow. onclick = myonclickmethodThis code will re-write the previousWindow. onclickThis event may also cause IE content leakage (sucks again ). Before ie supports Dom 2 event registration, we recommend that you use libraries to solve the problem, such as using Yui:

    Yahoo. util. event. addlistener (window, "click", myonclickmethod );

    This should also be a common sense problem, but it may be easy for new users to make mistakes.

  9. Focus poocus

    CreateInputText element, and then move the focus to it. It is reasonable to say that such code should be natural:

    VaR newinput = Document. createelement ("input ");
    Document. Body. appendchild (newinput );
    Newinput. Focus ();
    Newinput. Select ();

    However, ie will report an error (sucks again and again ). The reason may be that when you executeFouce ()The element is not yet available. Therefore, we can delay the execution:

    VaR newinput = Document. createelement ("input ");
    Newinput. ID = "thenewinput ";
    Document. Body. appendchild (newinput );
    SetTimeout (function () {// here I used closure to rewrite it. If you are interested, you can compare it with the original article.
    Document. getelementbyid ('thenewinput'). Focus ();
    Document. getelementbyid ('thenewinput'). Select () ;}, 10 );

In practice, there are many more JavaScript traps, mostly because the parser implementation is not in place. These things generally do not appear in textbooks. They can only be shared by developers. Thank God, we live in the Internet era. We can find answers to many problems in Google.

Conversion from realazy» nine traps and comments of JavaScript

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.