是否有可能让javascript构造函数返回不同的对象类型?

Man*_*ans 8 javascript constructor

我想做这样的事情:

function AjaxRequest (parameters) {
    if (window.XMLHttpRequest) {
        this = new XMLHttpRequest();
    else if (typeof ActiveXOBject != 'undefined')
        this = new ActiveXObject("Microsoft.XMLHTTP");
}

AjaxRequest.prototype.someMethod = function () { ... }
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Mat*_*ley 10

可以从构造函数返回不同类型的对象,但不完全像您尝试的那样.如果返回一个对象,而不是undefined(这是默认的返回值),它将"替换"它作为new表达式的结果.该对象不会从构造函数中获取其原型(并且x instanceof AjaxRequest将无法工作).

如果您想要这样做,这将让您关闭:

function AjaxRequest (parameters) {
    var result;

    if (window.XMLHttpRequest)
        result = new XMLHttpRequest();
    else if (typeof ActiveXOBject != 'undefined')
        result = new ActiveXObject("Microsoft.XMLHTTP");

    // result is not an AjaxRequest object, so you'll have to add properties here
    result.someMethod = function () { ... };

    // Use result as the "new" object instead of this
    return result;
}
Run Code Online (Sandbox Code Playgroud)


Che*_*eso 1

唔。不,我不这么认为。 this不可设置。您无法更改它,但可以向其添加属性。您可以进行导致this被设置的调用,但不能直接设置它。

你可以这样做:

function AjaxRequest (parameters) { 
    this.xhr = null;
    if (window.XMLHttpRequest) { 
        this.xhr = new XMLHttpRequest();  
    }
    else if (typeof ActiveXOBject != 'undefined') {
        this.xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
    }  
}

AjaxRequest.prototype.someMethod = function (url) { 
    this.xhr.open('Get', url, true);
    this.req.onreadystatechange = function(event) {
        ...
    };
    this.xhr.send(...);
};
Run Code Online (Sandbox Code Playgroud)

退一步来说,我认为你的设计不是很清晰。你想做什么?另一种问法是你正在拍摄的使用模型是什么?您想通过AjaxRequest哪些方法公开哪些动词?

如果你看一下 jQuery,他们的“ajax 请求”不是一个对象,而是一个方法。 $ajax()....

有什么想法?

这将决定您如何使用 xhr 属性,等等。