具有“onload”事件的 JavaScript 对象/回调生命周期
今晚我正在编写一个图像库,这让我想到了一个哲学问题
我创建了一个预加载的图像对象并为其设置了一个 onload 事件
... onmouseover = function() {
preloadActive = true;
imgPreload = new Image();
imgPreload.onload = function() {
preloadActive = false;
}
imgPreload.src = ...;
}
是全局变量
其中 imgPreload
和 preloadActive
现在 想象一下,在执行 onload()
之前,会触发一个新的 onmouseover()
。
运行一行代码创建一个新的图像对象,旧的图像对象失去最后一个链接并转到 Erebus,并等待垃圾收集器吃掉它。
问题在这里: 旧的对象实例不会立即销毁。没人知道它的 onload 事件会持续多久?您有这方面的跨浏览器经验吗?
谢谢你!
PS:我不担心 IE6
PPS:如果我有一个带有 setInterval 超时 ID 的对象,会发生什么?
obj.someVar = setInterval(...)
setInterval 是在我执行的那一刻停止的吗
obj = {}
?
I am coding an image gallery tonight and this led me to a philosophical question
I create a preloaded Image object and set an onload event for it
... onmouseover = function() {
preloadActive = true;
imgPreload = new Image();
imgPreload.onload = function() {
preloadActive = false;
}
imgPreload.src = ...;
}
Where imgPreload
and preloadActive
are global variables
Now imagine that a new onmouseover()
fires out before onload()
executes.
a line of code is run which creates a new image object, the old image object looses the last link and goes to Erebus, and is waiting for garbage collector to eat it.
The question goes here:
The old object instance is not destroyed immediately. Its onload event continues to live nobody knows for how long time? Do you have any cross-browser experience about that?
Thank you!
PS: I don't worry about IE6
PPS: What happens if I have an object with setInterval timeout ID inside?
obj.someVar = setInterval(...)
Is setInterval stopped the very moment I execute
obj = {}
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,对于初学者来说,全局变量不符合垃圾回收的条件(这通常是内存泄漏问题的原因,也是避免一起使用全局变量的众多原因之一)。
话虽如此,请阅读这篇文章埃里克·利珀特。它很旧,但我仍然认为它非常相关。
Well, for starters, global variables aren't eligible for garbage collection (which is usually the cause of memory leak issues and is one of many reasons to avoid using global variables all together).
Having said that, please read this article by Eric Lippert. It's old, but I still think it is quite relevant.