0

I have a problem with javascript namespaces.

I want to call secondMethod from ajax callback function but I don't know how to get reference to it. I have done it like that yet. But variable thisReference seems to me awkward. And whole construction is difficult to read.

So I'm writing there for help and answer how to rewrite it better.

var testObject = new TestObject();
testObject.firstMethod("hello world!");

function TestObject() {
    var thisReference = this;

    this.firstMethod = function(firstParam) {
        ajaxFunc(firstParam, function(ajaxResult) {
            thisReference.secondMethod(ajaxResult);
        });
    };

    this.secondMethod = function(secondParam) {
        alert("secondMethod " + secondParam);
    };

}

function ajaxFunc(hello, callBack) {
    callBack(hello);
}

Thanks a lot.

Ondra

Pranav
  • 8,563
  • 4
  • 26
  • 42

1 Answers1

1

Something like what you're doing is a common way to do it. Using:

var that = this;

or:

var self = this;

are common names to keep a hold of your original scope.

Another option (which I prefer) is to bind the this object to the method you're calling so that you have access to it in the callback. That would look like this:

this.firstMethod = function(firstParam) {
  ajaxFunc(firstParam, function(ajaxResult) {
    this.secondMethod(ajaxResult);
  }.bind(this));
};

Hope that helps.

Antiga
  • 2,264
  • 1
  • 20
  • 28