0

I have object myObject, inside I have function execute(), inside I have $.ajax({ which have complete: function(xmlHttp){. Inside that function I want to call setResult which is defined in the myObject. How to do that?

function myObject() {
    this.setResult = setResult;
    function setResult(result) {
        this.result = result;   
    }

    function execute() {
         $.ajax({
            complete: function(xmlHttp){
                (?) setResult(jQuery.parseJSON(xmlHttp.responseText));
            }
        });
    }

2 Answers 2

6

The standard way to do OOP is to use myObject as a constructor, and extend its prototype object with whatever needs to be inherited.

function myObject() {
    // constructor function
}

myObject.prototype.setResult = function (result) {
    this.result = result;   
}

myObject.prototype.execute = function() {
     $.ajax({
        context: this, // bind the calling context of the callback to "this"
        complete: function(xmlHttp){
            this.setResult(jQuery.parseJSON(xmlHttp.responseText));
        }
    });
}

var obj = new myObject();
obj.execute();

There's no requirement that it be done this way, but it's very common.

You need to keep in mind that the calling context of a function varies based on how that function is called. With respect to the complete: callback, jQuery sets the context, so it won't be your object unless you tell jQuery to make it that object or use some other way to bind the context.

jQuery's $.ajax method gives you a context: property that lets you set the calling context of the callbacks, as I've shown above.

Sign up to request clarification or add additional context in comments.

Comments

2
function myObject() {
    var that = this; // Reference to this stored in "that"
    this.setResult = setResult;

    function setResult(result) {
        this.result = result;   
    };

    function execute() {
         $.ajax({
            complete: function(xmlHttp){
                that.setResult(jQuery.parseJSON(xmlHttp.responseText));
        }
    });
}

Also you can check out jquery proxy and/or bind

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.