ES5 类中的 JavaScript 原型继承范围

时间:2021-03-26 17:54:28

标签: javascript angular xmlhttprequest ecmascript-5

我正在尝试为 Angular 编写 XMLHttpRequest 拦截器,但我不能简单地使用 HttpInterceptor,因为我需要拦截使用 XMLHttpRequest API 的第三方库。

整体波纹管解决方案有效,但我在类内部定义原型范围时遇到了麻烦。另外,如果我使用箭头函数,它就不会出现。

export class Interceptor {
    constructor(private config) {
        const XMLHttpRequestOpen = window.XMLHttpRequest.prototype.open;

        window.XMLHttpRequest.prototype.open = function (method, url) {
            if (url === this.config.url) { // this.config is out of scope of class
                this.onreadystatechange = function() {
                    this.setRequestHeader('Authorization', 'Bearer ...');
                };
            }
            return XMLHttpRequestOpen.apply(this, arguments);
        };
    }
}

欢迎任何简洁的解决方案。

1 个答案:

答案 0 :(得分:1)

将稍后要访问的值存储在不是 this 属性的变量中,这样它就不会因重新绑定而丢失。

export class Interceptor {
    constructor(private config) {
        const XMLHttpRequestOpen = window.XMLHttpRequest.prototype.open;
        const configUrl = this.config.url;

        window.XMLHttpRequest.prototype.open = function (method, url) {
            if (url === configUrl) {
                this.onreadystatechange = function() {
                    this.setRequestHeader('Authorization', 'Bearer ...');
                };
            }
            return XMLHttpRequestOpen.apply(this, arguments);
        };
    }
}
相关问题