Closing JavaScript and cloning names

Are variables defined inside an internal function that have the same name as a variable in an external function isolated from an external variable?

function() { var myTest = "hi there"; ( function( myTest ) { myTest = "goodbye!"; } )(); console.log( myTest ); // myTest should still be "hi there" here, correct? } 

Naturally, if I did not declare myTest inside the internal function, this would create a closing and changing the original. I just want to make sure that the variables declared inside the inner function are always isolated from this function, even if their name may conflict with the outer scope.

+6
source share
2 answers

Yes, they do effectively. Each function creates a new region, and the closest region in which the requested variable is declared always takes precedence. No exceptions. *


* Indirect eval

+11
source

Just for the sake of completeness. In these very similar examples, here's what happens without a parameter

 var x = 'a'; ( function( ) { //note that there is no parameter here x = 'b'; alert('inner:'+x); //b } )(); alert('outer:'+x); //b 

and var with the same name

 var x = 'a'; ( function( ) { var x = 'b'; alert('inner:'+x); //b } )(); alert('outer:'+x); //a 
+1
source

Source: https://habr.com/ru/post/910257/


All Articles