我有c++背景,正在学习javascript。webgl上的Mozilla教程的代码类似于下面(底部的实际代码和链接)。我试图理解为什么"onload“回调函数中的代码总是会被执行。在我看来,Image对象实例应该在下面的代码中进行垃圾回收。所以理论上它可以在加载完成并调用"onload“回调之前被垃圾回收。
function foo()
{
image = new Image();
image.onload = function()
{
/*stuff to do when image gets done loading */
Console.log(image.width);
}
image.src = url;
}我唯一的想法是,使用"image.width“的函数--函数对象必须将图像实例保存在内存中。但这将是一个循环引用,因为该函数只存在于图像对象本身;该函数对象的唯一引用AFAIK是它的onload回调属性。所以循环引用(image->onload->function->image->...)应该是垃圾回收的。
似乎我不理解什么,或者在图像加载和垃圾收集之间存在竞争条件。
显示循环引用岛不再可达的JS引用应该被垃圾回收。https://javascript.info/garbage-collection
教程链接:https://developer.mozilla.org/en-US/docs/Web/API/WebGL
function loadTexture(gl, url) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Put a single pixel in the texture until it loads
const level = 0; const internalFormat = gl.RGBA; const width = 1; const height = 1; const border = 0; const srcFormat = gl.RGBA; const srcType = gl.UNSIGNED_BYTE; const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,width, height, border, srcFormat, srcType, pixel);
const image = new Image();
image.onload = function() {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,srcFormat, srcType, image);
// WebGL1 has different requirements for power of 2 images vs non power of 2 images so check if the image is a power of 2 in both dimensions.
if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
gl.generateMipmap(gl.TEXTURE_2D); // Yes, it's a power of 2. Generate mips.
} else {
// No, it's not a power of 2. Turn off mips and set wrapping to clamp to edge
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
};
image.src = url;
return texture;
}
//irrelevant, but including for completeness
function isPowerOf2(value)
{
return (value & (value - 1)) == 0
}发布于 2019-07-04 08:54:30
当您为image.src赋值时,Image对象将被添加到浏览器的内部队列中,以供异步加载的所有外部对象使用。此队列可防止对象在函数返回时立即成为垃圾。只有当浏览器管理加载这些对象的过程时,队列才是必需的--它需要保存正在加载的对象,以便在从服务器获得响应时知道要做什么。
加载图像时,其onload函数将添加到事件队列中,并且由于它通过image变量(以及函数的this上下文和函数的Event参数)对对象进行引用,因此在函数运行时使对象保持活动状态。
一旦onload函数返回,图像将变成垃圾(因为它不会保存image anywhere的值)。
https://stackoverflow.com/questions/56878931
复制相似问题