DOM对象是否会在JavaScript中收集垃圾? [英] Do DOM objects get garbage collected in javascript?

查看:160
本文介绍了DOM对象是否会在JavaScript中收集垃圾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var domElementReference = $(document.createElement('div')); 

如果我实际上没有将它插入页面(一次<$如果没有:如果我有一个构造函数可以创建DOM元素,那么是否存在?c $ c> domElementReference 超出了作用域)?

一个自动的方式来清除他们在JavaScript?



我将它们追加到一个元素上,然后使用

  myChildNode.parentNode.removeChild(myChildNode); 

但是,当对象超出范围时,我不得不手动调用函数,这种混淆整个垃圾收集的想法。任何模式到
自动销毁对象?

解决方案

如果元素没有被插入到DOM中,其他参考文献存在,那么是的,他们将被垃圾收集,就像任何其他变量一样。



现代浏览器使用Mark-and-Sweep算法进行垃圾收集,这意味着垃圾收集器将查找并垃圾收集无法访问的对象。如果您在函数中创建元素,但不要在其他地方分配引用或不将其插入DOM,那么在函数完成后,它们将有资格进行垃圾回收。



不需要手动尝试释放JavaScript中的内存,它全部隐式处理。




var domElementReference = $(document.createElement('div'));

Will the DOM element get destroyed if I don't actually insert it on the page (once domElementReference gets out of scope)?

If not: If I have a constructor-function that creates DOM elements, is there an automatic way to clear them in javascript?

What I tought was to append them on an element, and then use

myChildNode.parentNode.removeChild(myChildNode);

But than again I have to manually call the function when the object is getting out of scope, and it kind of messes up the whole 'garbage-collection' idea. Any patterns to automatically destroy the object?

解决方案

If the elements haven't been inserted into the DOM and no other references exist, then yes they will be garbage collected, just like any other variables.

Modern browsers use a Mark-and-sweep algorithm for garbage collection, this means the garbage collector will look for and garbage collect objects that are unreachable. If you create elements in your function, but don't assign a reference elsewhere or don't insert them into the DOM, then they will be eligible for garbage collection after the function completes.

There is no need to manually try to free memory in JavaScript, it is all handled implicitly.

这篇关于DOM对象是否会在JavaScript中收集垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆