typescript - Failed to construct 'XMLHttpRequest' : Please use the 'new' operator, 这个DOM对象的构造函数不能作为函数调用

标签 typescript constructor xmlhttprequest

export default class Promise extends XMLHttpRequest {
    constructor(url: string, type: string) {
        super();
        config.url = url;
        config.requestType = type;
    }
}

我在这里创建了一个扩展类 XMLHttpRequest 的类 promise 。 然后我尝试使用下面给定的方法访问这个类。

let prom = new Promise('api/200', 'get');

进入 super 调用时出现如下错误

Failed to construct 'XMLHttpRequest': Please use the 'new' operator, this DOM object constructor cannot be called as a function

最佳答案

这可能是因为 XMLHttpRequest 是一个托管对象,它们在扩展时有时会出现错误。

幸运的是,如果你用 es6 类扩展它,情况就会改变。
编译时:

class RequestPromise extends XMLHttpRequest {
    constructor() {
        super();
    }
}

对于 es5 你得到:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var RequestPromise = (function (_super) {
    __extends(RequestPromise, _super);
    function RequestPromise() {
        _super.call(this);
    }
    return RequestPromise;
}(XMLHttpRequest));

但是当使用目标 es6 编译它时,它会保持类不变:

class RequestPromise extends XMLHttpRequest {
    constructor() {
        super();
    }
}

如果你尝试它应该工作得很好

关于typescript - Failed to construct 'XMLHttpRequest' : Please use the 'new' operator, 这个DOM对象的构造函数不能作为函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40794571/

相关文章:

typescript - 在没有 'Document' 的情况下从 Mongoose 模式中提取 TS 接口(interface)?

javascript - Redux 操作 typescript 返回类型不起作用

javascript - 如何在 ionic 3 中实现 LinkedIn 登录?为什么 Linked In Login 不起作用?

.net - .NET 中不正确的新 Uri(base,relative) 行为

javascript - 无法重写 XMLHttpRequest 上的 getResponseHeader 方法

Angular 10 : Date range picker - calender opens at wrong place

java - 多类图形用户界面

java - 从子类构造函数调用 super 构造函数是否会在内存中创建父类(super class)的对象?

c# - 调试 XMLHttpRequest POST

javascript - 你如何使用pdf.js获取客户端存储的pdf的文本内容?