Hubert  Lin
Hubert Lin

Reputation: 97

How do JS function object store in memory?

It is said that 'almost everything is an object', including functions.

So, what exactly happened in memory when I do something like:

function func(){
    // do something
}
var f = func;
f()


In my opinion, it first create an object instance for 'function func', then it cloned(deep copy, I guess) 'function func' and assigned it to the container 'var f'.

Is that right?
Or, how does it work?
Thanks!

Upvotes: 2

Views: 727

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075367

In my opinion, it first create an object instance for 'function func'

Yes, that was when it processed the function func() { } part

, then it cloned(deep copy, I guess) 'function func' and assigned it to the container 'var f'.

No, not at all. What's stored in f is a value called an "object reference" (or frequently just "reference"). Think of it as a number that the JavaScript engine can use to find the object elsewhere in memory. (We cannot see the actual value, but we don't ever need to.)

So when all of your code has run, and before any garbage collection is done, you have this in memory (leaving out some unnecessary detail):

func:Ref89895−−−+
                |
                |      +−−−−−−−−−−−−−−−−−−−−+
                +−−−−−>| function           |
                |      +−−−−−−−−−−−−−−−−−−−−+
                |      | name: "func"       |
f:Ref89895−−−−−−+      | length: 0          |
                       | ...                |
                       +−−−−−−−−−−−−−−−−−−−−+

There's func, which is the automatic binding (waves hands, basically a variable) created by function func() { } in the current context, and f, the variable you've assigned a copy of its value to (shown as Ref89895, but again, we never actually see these values).

Upvotes: 4

Related Questions