Programming traps that beginners should understand: JavaScript posts

Source: Internet
Author: User
Tags arrays join tostring hasownproperty

For beginners of programming language friends, often make some more "classic" mistakes. In this series of articles, we'll show you how to get beginner programming friends to avoid some basic bugs and learn how to program and develop code correctly.

In this article, we describe the issues and techniques that need to be noted in the development of 5 JavaScript code.

Redundant DOM operations

Dom operations are known to be more heavyweight. Effective restrictions on interaction can greatly help you improve the performance of your code. Look at the following code:

Anti-pattern

for (var i = 0; I < 100; i++) {

var li = $ ("<li>"). HTML ("This is List item #" + (i+1));

$ ("#someUL"). Append (LI);

}

This code loops through the DOM100, but creates 100 jquery objects. A better way is to use the document fragment, or create a string to contain 100

element, and then add it to the DOM. You only need to perform a DOM operation here.

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 calls only one DOM operation at a time, but a large number of string concatenation operations are used. In addition to using string concatenation, we can use arrays to 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 into the array, and then call the Join () method to connect. In JavaScript, this is the most efficient string concatenation operation without using the template class library and outside the framework.

Online debugging

Inconsistent variable and method name

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

var foo = "Bar";

var plant = "green";

var car = "Red";

If you add a variable called "something" may not be so appropriate, you should keep the name consistent. That's why in some programming languages, we use uppercase variable names to represent constants.

For methods, we also need to be consistent, as follows:

function subtractfive (number) {

return number-5;

}

If you have more than one minus 5 method, then if you define plus 5 methods, you should use the following naming method:

function addfive (number) {

return number + 5;

}

Sometimes if you define a return method, then the general use of getxxx (), if you just perform the operation does not return, then it is best to use the Doxxx () method name.

Constructor methods are best used in a naming style similar to other languages, with the first letter capitalized as follows:

function Gbin1 (color) {

This.color = color;

}

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

In for.. Using hasOwnProperty method in loop

Arrays are not associated in JavaScript. And the object is Hashtable type. You can use for ... In loop to iterate over the object properties. As follows:

For (Var prop in Someobject) {

Alert (Someobject[prop]); Alert ' s value of

}

The problem, however, is that the above code loops through all the attributes in the Proptype chain, and sometimes it goes wrong, and you might just want to use the actual properties. Using 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

}

}

This method can help you get the actual property values that exist.

Comparing Boolean values

Comparing Boolean values is a waste of computational time. Take a look at the following example:

if (foo = = True) {

Do something for True

} else {

Do something for false

}

Note that the above ==true condition is very unnecessary because Foo is a Boolean in itself. If you compare, you should use the following code:

if (foo) {

Do something for True

} else {

Do something for false

}

or test Foo to False, as follows:

if (! Foo) {

Do something for True

}else {

Do something for false

}

Event Bindings

Events are a very complex topic in JavaScript. The times when we used inline Oncick events have passed.

We should use event bubbling or delegation.

For example, if we need to show a group of pictures to Lightbox window. So the following code you should never use.

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

});

Writing this way causes binding events to each link element, preferably bound to the specified picture container, as follows:

$ ("#grid-container"). On ("Click", "a", function (event) {

Calllightbox (Event.target);

});

Online debugging

Avoidance of redundancy comparisons

In JavaScript and PHP:

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

Php

Return (something ())? True:false;

But the conditional comparison always returns TRUE or FALSE, so you don't need to add the return value clearly. The following code can be:

Javascriptreturn foo.tostring ()! = = "";

Php

return something ();

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

Source: Programming Traps that beginners should understand: JavaScript text

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.