Failed to override the getResponseHeader method on

2019-05-22 22:56发布

问题:

I was trying to override the getResponseBody method on XMLHttpRequest object. The code looks so:

xhr.onreadyStateChange = function(){
    if (xhr.readyState !== 4) {
        return;
    }
    if (xhr.status === 200) {
        // callback to handle the result
    } else {
        var _orig = xhr.getResponseHeader;
        xhr.getResponseHeader = function(name){
            return decodeHeader(_orig.apply(xhr,[name]));
        };
        // callback to handle the failure
    }
}

It throws an error "Object doesn't support this property or method" when calling the _orig.apply.

Any idea? Thanks.

PS: I create a new XHR object every time and do not reuse the old one.

回答1:

XMLHttpRequest is a host object (i.e. an object provided by the environment to represent something about the environment rather than part of the language), and host objects can essentially do whatever they like. They're not bound by the same rules as built-in objects. IE is particularly notable for making use of this freedom and many of its host objects (including XMLHttpRequest) do not behave as one might hope.

For this reason, it's better not to try and add or change any property of any host object. Instead, write your own XMLHttpRequest wrapper.