Search code examples
javascriptobjectactivexobject

Binding methods to object that returns other object


Let's say I have a following class:

var ie = function() {
    return new ActiveXObject('InternetExplorer.Application');
}

Now I'd like to alias IE's Navigate method, e.g.:

ie.prototype.goto = function() {
    this.Navigate('http://www.google.com'); // where 'this' should be ie
}

Of course, that does not work, I assume it's because the class is not aware of its "type change" before it returns it. So how do I bind the .goto() method to [Internet Explorer] rather than to [object Object]? From what I understand that's when call(), apply() or bind() come in handy, but I don't really know how to use them.


Solution

  • You can add the function to your objects before you return them:

    var ie = function() {
        var ieObj = new ActiveXObject('InternetExplorer.Application');
        ieObj.goto = function () { ieObj.Navigate('http://www.google.com'); };
    
        return ieObj;
    };
    
    var nav = ie();
    nav.goto();
    

    new ActiveXObject() doesn't return an instance of ActiveXObject, so there's no prototype that you could modify in order to have all the instances you create automatically have a particular method. Even if you could do that, it would mean that all ActiveXObjects you created would have that method, which wouldn't be a desirable situation.