开发者

Is it possible to have a javascript constructor return different object types?

开发者 https://www.devze.com 2023-03-04 13:27 出处:网络
I would like to do something like this: function AjaxRequest (parameters) { if (window.XMLHttpRequest) {

I would like to do something like this:

function AjaxRequest (parameters) {
    if (window.XMLHttpRequest) {
        this = new XMLHttp开发者_StackOverflow中文版Request();
    else if (typeof ActiveXOBject != 'undefined')
        this = new ActiveXObject("Microsoft.XMLHTTP");
}

AjaxRequest.prototype.someMethod = function () { ... }

Is there a way to do this?


It is possible to return a different type of object from a constructor, but not exactly like what you're trying to do. If you return an object, instead of undefined (which is the default return value), it will "replace" this as the result of the new expression. The object won't get its prototype from the constructor though (and x instanceof AjaxRequest won't work).

This will get you close if that's how you want to do it:

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;
}


Hmm. No, I don't think so. this is not settable. You cannot change it, though you can add properties to it. You can make calls that cause this to be set, but you cannot set it directly.

You can do something like 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(...);
};

Stepping back, I think your design isn't very clear. What is it that you're trying to do? Another way to ask that is What is the usage model you're shooting for ? What verbs do you want to expose from AjaxRequest What methods?

If you look at jQuery, their "ajax request" is not an object, it's a method. $ajax()....

What's your idea?

That will determine how you use the xhr property, and so on.

0

精彩评论

暂无评论...
验证码 换一张
取 消