Programming traps for beginners: javascript

Source: Internet
Author: User
Tags hasownproperty

For beginners of programming languages, they often make some "classic" errors. In this series of articles, we will introduce how to help beginners avoid some basic errors and learn how to properly program and develop code.

In this article, we will introduce the five issues and skills that need to be paid attention to during javascript code development.

Redundant DOM operations

DOM operations are widely known as heavyweight. Effectively limiting interactions can greatly improve the performance of your code. Take a look at the following code:

// Anti-pattern

For (var I = 0; I <100; I ++ ){

Var li = $ ("<li> commandid .html (" This is list item # "+ (I + 1 ));

 

$ ("# SomeUL"). append (li );

}

This code is cyclically modified to DOM100 times, but 100 jQuery objects are created. A better way is to use the document fragment or create a String to contain 100

And then add it to the DOM. Here you only need to perform the DOM operation once.

Optimized Code:

Var liststring = "";

For (var I = 100; I> 0; I --){

Liststring + = "<li> This is list item #" + (99-I );

}

Document. getElementById ("someUL"). innerHTML (liststring );

The above Code only calls the DOM operation once, but uses a large number of string connection operations. In addition to string connection, we can use Arrays for display.

Var liststring = "<li>"

Var lis = [];

For (var I = 100; I> 0; I --){

Lis. push ("This is list item #" + (99-I ));

}

Liststring + = lis. join ("</li> <li>") + "<li> ";

Document. getElementById ("someUL"). innerHTML (liststring );

When creating a large number of strings, save each string to the array and call the join () method to connect. In javascript, this is the most efficient way to connect strings outside the framework without using the template class library.

Online debugging

The variables and method names are inconsistent.

This may not be a performance issue, but it is very important for programming, especially when you need to maintain others' code. Take a look at the following example:

Var foo = "bar ";

Var plant = "green ";

Var car = "red ";

If you add another variable named "something", it may not be so appropriate. You should keep the name consistent. This is why in some programming languages, we use uppercase variable names to represent constants.

For methods, we also need to maintain consistency as follows:

Function subtractFive (number ){

Return number-5;

}

If you have more than one minus five method, you should use the following naming method if you define adding five methods:

Function addFive (number ){

Return number + 5;

}

Sometimes if you define a return method, getXXX () is generally used. If you only execute the operation and do not return the result, it is best to use the doXXX () method name.

It is recommended that the constructor method use a naming method similar to other languages. The first letter is capitalized, as follows:

Function Gbin1 (color ){

This. color = color;

}

In any case, you should try to make your name more meaningful and give more information to others.

Use the hasOwnProperty METHOD in THE for .. in Loop

Arrays are not associated in javascript. Objects are of the hashtable type. You can use... In loop to iterate object attributes. As follows:

For (var prop in someObject ){

Alert (someObject [prop]); // alert's value of property

}

However, the problem is that the above Code loops through all the attributes in the proptype chain. Sometimes this will cause errors. You may just want to use the actual attributes. The hasOwnProperty method can help you solve this problem.

For (var prop in someObject ){

If (someObject. hasOwnProperty (prop )){

Alert (someObject [prop]); // alert's value of property

}

}

This method can help you get the actual attribute values.

Compare boolean values

Comparing a boolean value is a waste of time. Let's take a look at the example below:

If (foo = true ){

// Do something for true

} Else {

// Do something for false

}

Note that the = true condition above is unnecessary because foo itself is a boolean value. Use the following code for comparison:

If (foo ){

// Do something for true

} Else {

// Do something for false

}

Or test if foo is false, as follows:

If (! Foo ){

// Do something for true

} Else {

// Do something for false

}

Event binding

Events are a complex topic in javascript. In the past, the oncick event in the industry has passed ..

We should use the event bubbling or delegation.

For example, if we want to display a group of images in a lightbox window. You should never use the following code.

Here we use jQuery as an example.

HTML:

<Div id = "grid-container">

<A href?“someimage.jpg "> </a>

<A href?“someimage.jpg "> </a>

<A href?“someimage.jpg "> </a>

.......

</Div>

Javascript (not recommended ):

$ ('A'). on ('click', function (){

CallLightbox (this );

});

This will cause binding events to every link element. It is best to bind events to the specified image container, as shown below:

$ ("# Grid-container"). on ("click", "a", function (event ){

CallLightbox(event.tar get );

});

Online debugging

Avoid redundancy comparison

In javascript and PHP:

// Javascriptreturn foo. toString ()! = ""? True: false;

// Php

Return (something ())? True: false;

However, true or false is always returned for condition comparison, so you do not need to explicitly add the return value. Run the following code:

// Javascriptreturn foo. toString ()! = "";

// Php

Return something ();

I hope you can understand and understand how to avoid code writing problems. If you have other examples, please share them with us!

Source: programming traps Beginners should understand: javascript

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.