简体   繁体   中英

var variable reassignment within function

I don't understand why a var variable can be reassigned within a function, but the change also applies outside of the function. Why/How?

var c = 1;

function Fn() {
c = 2;
}
Fn();
c; // 2

Why isn't the value 2 limited to the scope of the function? When I write c = 2 within a function, does the javascript engine automatically hoist a new var c outside of the function and assigns it the value undefined , which is then changed to 2 once Fn() is called?

It applies outside the function because, inside the function, you are changing the variable .

You are not creating a new variable that exists only inside the function.


Why isn't the value 2 limited to the scope of the function?

You didn't use var , let , const or any other method to create a variable in the scope of the function.

You are accessing the variable you already created in the wider scope.


When I write c = 2 within a function, does the javascript engine automatically hoist a new var c outside of the function and assigns it the value undefined, which is then changed to 2 once Fn() is called?

No. There isn't a new variable. There is only the c you already created outside the function.

This is a common complaint about javascript. Since you used "Var" it has a global scope, so even though you're within a new function when you use c=2 since it's already defined globally it's changed globally. Using "Let" helps define things local to the function and "const" defines globals as constants so they cannot be changed. This issue is particularly fun when you have two global variables with the same name in different JavaScript files and then reference both files to be used on a page. Globals should be used with caution.

When you start run this program, engine will store your variable which declared with "var" keyword in global object (window) then move on to get in the function, Engine will create Special Scope for function is called "Function Execution Context" ( FEC ) every declaration within the function will be available in this scope( FEC ), so when Engine execute body of your function will find re-assignment for variable is called "c" , it will looking for it in current scope, if didn't find it, will move on parent scope, in this case, Global Scope is its destination, will find the searched variable and then re-assign it with new value.

Read this wonderful article -> execution-context-how-javascript-works-behind-the-scenes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM