Why does the object created and returned by the function continue to exist after the completion of the function?

I read that each function has its own stack, which means that when a function ends, its variables are no longer stored in memory. I also read that objects are returned by reference.

Consider the following example:

function getObject() {
 var obj = {name: "someName"};
 return obj;
} //At the end the locals should disappear


var newObj = getObject();// Get reference to something that is no longer kept in the stack,
console.log(newObj);//
Run code

So, if the return value of the function is a reference for an object that no longer exists (on the stack), how do we still get the correct value? In C(language), to return a pointer to a local variable is insane.

+4
source share
2 answers

-, : , JavaScript.

:

, , . . , , , :

                    +−−−−−−−−−−−−−−−−−−+
                    |     (object)     |
                    +−−−−−−−−−−−−−−−−−−+
[obj:Ref11254]−−−−−>| name: "someName" |
                    +−−−−−−−−−−−−−−−−−−+

obj, (Ref11254, , , , ). , obj (Ref11254), obj () . , , , - — , newObj.

:

JavaScript- ( , ). , , . ( ), . (? , .)


, , :

function getFunction() {
    var x = 0;
    return function() {
        return x++;
    };
}
var f = getFunction();
console.log(f()); // 0
console.log(f()); // 1
console.log(f()); // 2

getFunction ( ), x! " ", getFunction. ?!

, . - (). , ( ) , LexicalEnvironment, getFunction. , getFunction LexicalEnvironment, ( ) getFunction. ( getFunction , , .)

, JavaScript . , . , , (, x ), ( , ) .

( ).

+7

Source: https://habr.com/ru/post/1693118/


All Articles