【发布时间】:2019-07-03 23:11:06
【问题描述】:
我来自 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_API/Tutorial/Using_textures_in_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
}
【问题讨论】:
标签: javascript image reference garbage-collection