简体   繁体   中英

Javascript “saves” function data in memory?

Example :

var myFunctArray=new Array();

for(var i=0; i<10; i++) {
    addValues(i);
}

function addValues(myPoint)
{
    myFunct=function () {
        var myVar="Line " + myPoint;
        console.log(myVar);
    }    

    myFunctArray.push(myFunct);        
}

myFunctArray[3]();

when I call the 4° function, how can it remembers the value of myPoint? In fact it is Line 3 the output, so myPoint value must be "stored" somewhere, for each function.

So, it stores 10 "definitions" of myFunct in the stack memory?

Hope it is clear what I mean.

It's called a closure. Any variables that are currently in scope when you create a new function are associated with that closure.

So, it stores 10 "definitions" of myFunct in the stack memory?

Yes, it does.

Your array contains ten closures, each of which has captured its own version of myPoint .

Thiefmaster answered your question pretty much. Yes, this code will use more and more memory, depending on how many closures your array contains. It has to be said that most modern engines will assign a reference to the function assigned to the MyFunct variable and a specific "call object" that contains the closure vars. In other words, your array will look something along the lines of:

myFuncArray[0] = {call:
                     {myPoint:'Whatever value was passed to the addValues function the first time'},
                  valueOf: myFunct};
//the actual value is a reference to myFunct
//JS provides an implicit link to the call property, which is bound to this particular reference
myFuncArray[1] = {call:
                     {myPoint:'The value passed to addValues the second time'},
                 valueOf: myFunct};

You don't have access to the object as such, but this is just the way to think of how JS will keep things organized in memory.
Slightly off topic, but you're creating an implied global with your MyFunct variable:

function addValues(myPoint)
{
    var anotherClosureVar = 'This will be accessible, too: it\'s part of the closure';
    var myFunct = function()
    {//use var to declare in addValues scope, instead of using an implied global
        var myVar="Line " + myPoint;
        console.log(myVar);
        console.log(anotherClosureVar);//will work, too
    };
    myFunctArray.push(myFunct);
}

All in all, if this is your code, memory shouldn't be that big of an issue. Even if this code were to run on an old JScript engine, it'll take some time before you've used up a meaningful amount of memory.
Still, it's a good habit to think about stuff like this, and I do hope I made sense here, I'm not a native speaker, which makes explaining the more abstract aspects of JS somewhat tricky

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