繁体   English   中英

Javascript“保存”功能数据在内存中?

[英]Javascript “saves” function data in memory?

范例

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]();

当我调用4°函数时,它如何记住myPoint的值? 实际上,它是第3行的输出,因此对于每个函数,myPoint值必须“存储”在某个位置。

那么,它在堆栈存储器中存储myFunct 10个“定义”吗?

希望我的意思很清楚。

这称为关闭。 创建新函数时,当前作用域中的所有变量都与该闭包关联。

那么,它在堆栈存储器中存储myFunct的10个“定义”吗?

是的,它确实。

您的数组包含十个闭包,每个闭包都捕获了自己的myPoint版本。

小偷大师几乎回答了您的问题。 是的,此代码将使用越来越多的内存,具体取决于数组包含的闭包数量。 必须说,大多数现代引擎都会为分配给MyFunct变量的函数和包含闭包var的特定“调用对象”分配一个引用。 换句话说,您的数组看起来将类似于:

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};

您没有访问此类对象的权限,但这只是思考JS如何将事物组织在内存中的一种方式。
主题略有偏离,但您正在使用MyFunct变量创建隐式全局变量:

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);
}

总而言之,如果这是您的代码,那么内存就不应该成为大问题。 即使此代码在旧的JScript引擎上运行,也要花一些时间才能用完有意义的内存。
不过,考虑这样的事情还是一个好习惯,我希望我在这里很有意义,因为我不是母语人士,这使得解释JS更抽象的方面有些棘手。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM