简体   繁体   English

如何在javascript中的函数对象内部进行变量内存分配?

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

How are the variables scoped, initialized and used outside and inside javascript functions? 如何在javascript函数的内部和外部对变量进行范围划分,初始化和使用? 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. 我了解到,在JS执行中,首先会扫描代码以查找所有变量声明,然后执行函数。

var x defined inside calculator object is value type as its integer. 在计算器对象内定义的var x是值类型为其整数。

getx being nested function and as per closure will have access to variable "x" even after return of getx is executed. getx是嵌套函数,每个闭包即使执行了getx返回后也可以访问变量“ x”。

First output for calculator.x is as expected=5; 计算器.x的第一个输出为expected=5;

Second output for calculator.x is as expected=10; 计算器.x的第二个输出是expected=10; (as x is modified) (因为x被修改)

Third output for calculator.getx() is =5; Calculator.getx calculator.getx()第三输出为= 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. “ x”是值类型,它也应该在函数范围内具有修改后的值,并且第三个输出应为= 10。 What am I missing here? 我在这里想念什么?

calculator.x = 10 

adds x to the property of the function 将x添加到函数的属性
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 计算器现在引用对象{x:x,getx},并且您要更改的值不是变量x而是计算器的属性x
to access the change in property you will need to output this.x 要访问属性更改,您将需要输出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 为了证明这一点,请看下面的代码,显然变量x并未更改,相反,属性正在更改,getx无法访问该属性

 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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