简体   繁体   中英

Variables inside functions + callbacks

I have a function (zReaderRequest, see below) where a callback function is using a variable that is local to this first function, ie "rq" here. Will new calls to the function zReaderRequest create a new variable "rq" or will the callback functions use the same "rq"? If they use the same, what can I do? Create an object that holds this function, or?

function zReaderRequest(zURL, outputElt, displayFun) {
    switch (outputElt.dataset.zReaderStatus) {
    case undefined:
        outputElt.dataset.zReaderStatus = "requested";
        var rq = new XMLHttpRequest();
        rq.onload = function() {
            if (displayFun(rq, outputElt))
                outputElt.dataset.zReaderStatus = "received";
            else
                outputElt.dataset.zReaderStatus = "failed";
        };
        rq.open("GET", zURL, true);
        rq.setRequestHeader("Zotero-API-Version", "2");
        rq.send();
        break;
    }
}

Where do I learn this so I do not have to ask questions like this one? ;-)

The call-back function is a closure — it references the independent variable rq . Every call to that call-back will use the same rq variable. However, if you call zReaderRequest another time, it will create a new closure that refers to a different object stored in a different rq (since rq comes into existence when the zReaderRequest function is entered). I think this is the behavior you want for that code.

As to where to learn about all this stuff, I recommend the JavaScript Guide at the Mozilla Developer Network. Closures are discussed in the chapter named (surprise!) Closures . Another good resource at MDN is A re-introduction to JavaScript (JS Tutorial) . They cover a lot of the same material, but with different exposition.

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