简体   繁体   中英

How variable memory allocation takes place inside function object in javascript?

How are the variables scoped, initialized and used outside and inside javascript functions? I have written following code:

 <div id="output"> </div> <script> var calculator = function() { var x = 5; getx = function(){ return x; } return { x:x, getx }; }(); document.getElementById("output").innerHTML = calculator.x; calculator.x=10; document.getElementById("output").innerHTML += " "+ calculator.x + " "+calculator.getx(); </script> 

I read that in JS execution, code is first scanned for all the variables declaration and then functions are executed.

var x defined inside calculator object is value type as its integer.

getx being nested function and as per closure will have access to variable "x" even after return of getx is executed.

First output for calculator.x is as expected=5;

Second output for calculator.x is as expected=10; (as x is modified)

Third output for calculator.getx() is =5; (I am not able to understand this)

"x" being value type, it should have modified value inside function scope too and third output should be=10. What am I missing here?

calculator.x = 10 

adds x to the property of the function
calculator now refers to the object { x:x, getx } and the value you are changing is not the variable x but the property x of calculator
to access the change in property you will need to output this.x

 <div id="output"> </div> <script> var calculator = function() { var x = 5; getx = function(){ return this.x; } return { x:x, getx }; }(); document.getElementById("output").innerHTML = calculator.x; calculator.x=10; document.getElementById("output").innerHTML += " "+ calculator.x + " "+calculator.getx(); </script> 

To prove it look at the below code, clearly the variable x was not being changed, instead the property was being change which getx could not access

 <div id="output"> </div> <script> var calculator = function() { var x = 5; getx = function(){ return x; } setx = function(a){ x = a; } return { x:x, getx, setx }; }(); document.getElementById("output").innerHTML = calculator.x; calculator.setx(10); document.getElementById("output").innerHTML += " "+ calculator.x + " "+calculator.getx(); </script> 

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