Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to do something like this:

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

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

Is there a way to do this?

like image 519
Mansiemans Avatar asked May 07 '11 11:05

Mansiemans


2 Answers

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;
}
like image 195
Matthew Crumley Avatar answered Sep 21 '22 20:09

Matthew Crumley


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.

like image 26
Cheeso Avatar answered Sep 17 '22 20:09

Cheeso