Javascript variable scopes can span multiple functions!

Source: Internet
Author: User

Today, we write a javascript code like this:

Function (){

...

For (I = 0; I <ABC. length; I ++ ){

...

B ();

...

}

...

}

 

Function B (){

...

For (I = 0; I <def. length; I ++ ){

...

}

...

}

These two JavaScript Functions. However, function a only executes a loop and jumps out of the for loop. It should have executed multiple cycles.

I checked the code all day and finally found the cause of the error.

Originally, there was a problem with the lifecycle management of JavaScript variables. The local variables I of functions a and B, JavaScript considers them to be the same variable.

In this way, after the loop is executed in function B, the I value in function a has exceeded the condition, so each time the for loop of function a is executed only once.

After I change I in function B to J, it will be normal!

It is indeed against common sense to manage the lifecycle of such variables. I am using IE7. I don't know if this is a javascript specification? Or is there a problem with the implementation of IE7 itself?

It seems that we must avoid using variables with the same name in Javascript encoding to avoid variable name conflicts. This problem is extremely hidden and hard to find!

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.