简体   繁体   English

我的对象被覆盖并丢弃了吗

[英]Is my object being overwritten and disposed

using Javascript. 使用Javascript。

I declare an image variable like so: 我像这样声明一个图像变量:

var myIMG = new Image();

I load up 100 images like this: 我像这样加载100张图片:

for (var test =0 ; test < 100; test++)
{
     myIMG.src = null;
     myIMG.src = {get new image from server somehow}
}

and this: 和这个:

for (var test =0 ; test < 100; test++)
{
     myIMG = new Image();
     myIMG.src = {get new image from server somehow}
     myIMG.src = null;
     delete myIMG
}

(code is for testing purposes) (代码用于测试)

What is the correct way to reduce memory consumption? 减少内存消耗的正确方法是什么?

Thanks 谢谢

You might be interested to know that JavaScript doesn't have a local scope for a for loop. 您可能想知道JavaScript没有for循环的本地作用域。 It's scoping is based on functions. 它的作用域基于函数。 Hence, you should not redeclare var myImg more than once in a function. 因此,您不应在函数中多次声明var myImg

Going back to your code, I would suggest that you only declare one new Image() (ie outside the loop), which should be more efficient 回到您的代码,我建议您只声明一个new Image() (即在循环外),这样应该更有效

var i, myImg = new Image();

for(i = 0; i < 100; i++) {
    myImg.src = getNewSource();
}

The delete property is meant for removing an item from an object. delete属性用于从对象中删除项目。 For example: 例如:

var myObj = { a: 2, b: 3 };
delete myObj.a;
// myObj will now be { b: 3 }

However, this does not necessary release the memory, but the reference to the item in the object. 但是,这不必释放内存,而是释放对对象中项目的引用。 The memory is claimed back by the JavaScript garbage collector (and you cannot trigger this in your code) JavaScript垃圾回收器收回了内存(您无法在代码中触发该内存)

Hope this helps 希望这可以帮助

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

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