Hoisting - Name resolution in Javascript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

   This question already has an answer here:
    * /questions/7506844/javascript-function-scoping-and-hoisting /questions/7506844/javascript-function-scoping-and-hoisting 9 answers

Answers

Did I understand correctly the reason for alerting 1

Yes

"But this does not mean that the value of a variable assignment does not replace the function"
What does the above line means ? (the misunderstood part)

It just means that although a function with name a is already defined, a = 10 is still going to be executed, i.e. after that line a does not refer to a function anymore but to 10.

I assume they wanted to relax the previous statement a bit and avoid that people incorrectly think that because the function declaration is executed first, the assignment would not take place anymore.


Function and variable declarations are hoisted to the top of the scope. So the code is equivalent to:

1:   var a = 1;
2:   function b () {
3:       function a() {}
4:       a = 10;
5:       return;
6:   }
7:   b();
8:   alert(a);

function a() {...} creates a symbol (variable) a in the local scope and its value is the very same function. The next line, a = 10;, then assigns a new value to that symbol, namely a number.

var a = 1;
function b () {
     function a() {} // creates a new local symbol `a`, shadowing the outer `a`
     // until here, `a` refers to the function created 
     // created by the above declaration
     a = 10; // now a new value is assigned to the local symbol/variable `a`
     // from here on, `a` is `10`, not a function
     return;
}
b();
alert(a);

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/12287049/name-resolution-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils