JavaScript Code
var str = "hi";
Memory allocation:
Address | Value | Description |
---|---|---|
...... |
... | |
0x1001 |
call object | Start of a call object's memory |
0x1002 |
0x00af | Reference to invoked function |
0x1003 |
1 | Number of references in this call object |
0x1004 |
str | Name of variable (in practice would not be in a single address) |
0x1005 |
0x1001 |
Memory address of "hi" |
...... |
... | |
0x2001 |
string | type identifier |
0x2002 |
2 | number of bytes |
0x2003 |
h | byte of first character |
0x2004 |
i | byte of second character |
When JS runs: var str = "hi";
by calling some function, it first hoists all variable declarations and creates a spot in memory for the variable. This might leave memory something like:
Address | Value | Description |
---|---|---|
...... |
... | |
0x1001 |
call object | Start of a call object's memory |
0x1002 |
0x00af | Reference to invoked function |
0x1003 |
1 | Number of references in this call object |
0x1004 |
str | Name of variable |
0x1005 |
empty | |
...... |
... |
In practice, the name of the variable, str
, would not be held in a single memory address. Also, the variable names and locations would not be stored in a fixed-memory array (possibly in a hash-table).
Next, the string "hi"
would be created in memory like:
Address | Value | Description |
---|---|---|
...... |
... | |
0x2001 |
string | type identifier |
0x2002 |
2 | number of bytes |
0x2003 |
h | byte of first character |
0x2004 |
i | byte of second character |
Finally, the pointer address of str
would be set to the memory address of "hi"
(0x2001
), leaving memory as indicated at the top of the page.
@mraleph,
(Question Summary: If the native call stack is used, and a function's
activation frame
is popped when the function returns, how do inner functions "walk up" to parent function'sactivation frame
to get a value).Thank you VERY much for your explanation! I thought I had some time when I started this post to work on my JSConf talk, but that time evaporated, so I am resuming it now. I owe you a dinner / beer / etc. If you are coming to JSConf, I can pay that debt sooner than later.
By
call object
I'm referring to whatever mechanism allows closures to work. For the following example:Some record (possibly stack frame / activation record) needs to exist for the inner function to find the value of i. I've assumed that an inner function's
call object
(oractivation record
) has a reference to its parentcall object
(oractivation record
), that i is retrieved by checking the currentcall object
for i and walking up to the parentcall objects
until i is found.I'm not sure how this would work with the native call stack. It's my (mis)understanding that the call stack is popped when the current function has completed running. If that's true, then I'm missing something else. Perhaps when a function is run and its
activation record
is created, the newactivation record
gets all of its parent references?Thanks again for your help!