首页 > 解决方案 > ES5 类中的 JavaScript 原型继承范围

问题描述

我正在尝试为 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);
        };
    }
}

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

标签: javascriptangularxmlhttprequestecmascript-5

解决方案


将稍后要访问的值存储在不是 的属性的变量中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);
        };
    }
}

推荐阅读