简体   繁体   中英

When declaring a function to a variable that variable stores the function or a reference?

as I have just learnt when you assign an object to a variable, or constant, in that variable it is not stored the actual object but a reference value to a certain point in the memory where the actual value of the object is stored. Thus, as I have also learnt function are objects. So, my question is. When you are declaring a function into a variable, is it the same process? The function is stored somewhere in the memory and the variable stores a reference value that points to a certain place in the memory?

Yes, functions are objects, and yes the value stored in a variable for any object is a reference to the object, not a copy of it. That includes functions.

You can easily see that by making a change to the function object:

 const f1 = function fn() { }; const f2 = f1; f1.someProperty = 42; console.log(f2.someProperty); // 42

When you do:

const f1 = function() { };

you get something like this in memory (details omitted) :

                       +−−−−−−−−−−−−−−−−−−+
f1:Ref13246−−−−−−−−−−−>|    (function)    |
                       +−−−−−−−−−−−−−−−−−−+
                       | name: "fn"       |
                       +−−−−−−−−−−−−−−−−−−+

Note the value in f1 , which I've shown here conceptually as Ref13246 . It tells the JavaScript engine where to find that object.

Now if you do:

const f2 = f1;

you have something like:

                 
f1:Ref13246−−−−−−+
                 |     +−−−−−−−−−−−−−−−−−−+
                 +−−−−>|    (function)    |
                 |     +−−−−−−−−−−−−−−−−−−+
f2:Ref13246−−−−−−+     | name: "fn"       |
                       +−−−−−−−−−−−−−−−−−−+

Notice how f2 and f1 have the same value in them, a reference that says where the function is.

Now when we do:

f1.someProperty = 42;

that modifies the function:

                 
f1:Ref13246−−−−−−+
                 |     +−−−−−−−−−−−−−−−−−−+
                 +−−−−>|    (function)    |
                 |     +−−−−−−−−−−−−−−−−−−+
f2:Ref13246−−−−−−+     | name: "fn"       |
                       | someProperty: 42 |
                       +−−−−−−−−−−−−−−−−−−+

You can see that new property on the function object regardless of which variable you get the reference from.

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