Invoke a javascript object method from within a callback

Viewed 20153

I define the following MyClass and its methods in a user script:

function MyClass() {
    this.myCallback = function() {
        alert("MyClass.myCallback()");
    };

    this.startRequest = function() {
        GM_xmlhttpRequest({
            'method': 'GET',
            'url': "http://www.google.com/",
            'onload': function (xhr) {
                myClassInstance.myCallback();
            }
        });
    };
}

var myClassInstance = new MyClass();
myClassInstance.startRequest();

This script works and the myCallback() method gets called once the GM_xmlhttpRequest completes.

However, it only works because the onload callback is referring to the global variable myClassInstance. If I update the onload callback to:

'onload': function (xhr) {
    this.myCallback();
}

Then I get the (Chrome) error:

Uncaught TypeError: Object [object DOMWindow] has no method 'myCallback'.

It seems this is being evaluated in the wrong context.

Is there a way to invoke the myCallback() method of myClassInstance without having to resort to using a global variable?

3 Answers
Related