简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM