How to structure javascript callback so that function scope is maintained properly

后端 未结 4 515
小蘑菇
小蘑菇 2020-12-13 02:56

I\'m using XMLHttpRequest, and I want to access a local variable in the success callback function.

Here is the code:

function getFileContents(filePat         


        
4条回答
  •  甜味超标
    2020-12-13 03:20

    In this scenario, test will be resolved as you'd expect it, but the value of this might be different. Normally, to preserve the scope, you would make it a parameter to the asynchronous function like so:

    function getFileContents(filePath, callbackFn, scope) {  
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                callbackFn.call(scope, xhr.responseText);
            }
        }
        xhr.open("GET", chrome.extension.getURL(filePath), true);
        xhr.send();
    }
    
    
    //then to call it:
    var test = "lol";
    
    getFileContents("hello.js", function(data) {
        alert(test);
    }, this);
    

提交回复
热议问题