开发者

Will this JavaScript code garbage-collect the way I expect?

开发者 https://www.devze.com 2023-02-21 04:24 出处:网络
function fetchXmlDoc(uri) { var xhr = new XMLHttpRequest(); var async = false; xhr.open(\"GET\", uri, async);
function fetchXmlDoc(uri) {
    var xhr = new XMLHttpRequest();
    var async = false;
    xhr.open("GET", uri, async);
    xhr.send();

    return xhr.responseXML;
}

Basically, when I call this function, will the xhr object get garbage-collected, or 开发者_开发问答will it stick around forever because the caller is holding on to xhr.responseXML? If it's the latter, would this solve it?

function fetchXmlDoc2(uri) {
    var xhr = new XMLHttpRequest();
    var async = false;
    xhr.open("GET", uri, async);
    xhr.send();

    var xml = xhr.responseXML;
    return xml;
}

Despite all my years of JS, the whole memory-management thing still manages to confuse me...


The responseXML property of the xhr object is a reference to the actual data object (just as you've implicitly assumed in the second piece of code: you're not copying the data, you're copying the reference).

So the xhr object will eventually get garbage collected. There is only one reference to it: right here in this function where it's created.

0

精彩评论

暂无评论...
验证码 换一张
取 消