JS variable promotion of a small pit

Source: Internet
Author: User

Long time did not write a blog, originally wanted to practice the end of the actual training project to sum up, did not expect to go back to school is not easy, recently in the production of web version of the resume, encountered a small problem, and now do not summarize after certainly busy, so long story short, seize the time to write down.

The JS syntax is more familiar to the classmate may know: JS is not block-level scope, there is a novice is prone to error where

 for (var i = 0; i <; i + +) {    setTimeout (function() {        console.log (i)    }, 1000*i)}

This code will output 10 10, rather than the expected,..., 10, because the scope of each loop is the same, so they share the same I, the problem is very simple, here is not elaborate, this time to say in the back

Note that the following code

Console.log (a)  //undefined
if (! a) {    var a = 1;} Console.log (a)  //1

If a does not exist, declare a variable A and copy it to 1, this code runs, the console will not unexpectedly print out 1, it seems that there is no problem, but actually what happened?

1. Declare all variables used in this scope to the header of the current scope, for this code, because JS has no block-level scope, equivalent to changing the code to

var A; / * Other variables * /

2. Execute the code after the declaration is complete

if (! a) {  //execute to here when a actually already declared, but no assignment     = 1;} Console.log (a);  1
/* Other statements */

It doesn't seem like much of a problem, but in some cases it's troublesome to not understand it, for example, when we're traversing the tree, we'll use recursion.

function Test () {    console.log ("test");     if (! a) {        var a = 1;    }     if (A < 3) {
a++; Test ();} }

What happens when you call test externally? At least I wrote this blog before I thought it would output 3 test, the fact is, the function constantly calls itself, endlessly print test

In the development of writing such a function, my idea is: in the recursive entry function to save an array, the process of executing the function will enter the different branches according to the conditions, in order to add or delete some elements in the array, and eventually return the array, the actual runtime found that the returned results do not meet the expectations, Each invocation seems to have re-declared an array, and if (!a) 's judgment does not look for the variable in the caller (parent scope), it scratching a long time before it suddenly reminds me of the summary of the variable promotion that I had seen before. Just because I thought it would happen in other languages, it was simple, it didn't work, It was a sanction today, and it took some time to think about it.

In fact, it is very simple to understand the problem, write the following code test

if (! a) {  //a not yet    declared =1// error uncaught referenceerror:a is not defined

Because the VAR keyword is not used, the JS engine does not perform a variable promotion on a, so a is an undeclared variable when it runs to the first line, and the error is directly

So how does test () exactly write?

var path; function Find (Orignnode, Desnode) {    if(!  Path) {
Console.log ("initialization path") = [Orignnode]; }
TEMP =/* other code */;
Find (Orignnode, temp);
}

At the moment, I have solved the obvious drawback: take the variable path in the parent scope, and the path is empty before each call to find, so the code looks uncomfortable, but due to the limited level, there is no better way to do it (there is a way to bind to the current function in the closure ( This.path), before the function return

var  This . Path; Delete  This . Path; return path;

Feel also not good where to go, if you have a good solution, welcome to leave a message below

In addition, to play a small advertising, but also I found the source of the problem is my personal homepage (http://iny7.com), the page is still in development, I hope you can get the guidance ^_^

JS variable promotion of a small pit

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.