Ciarán Tobin
Ciarán Tobin

Reputation: 7526

JavaScript class function this operator

I have a JS class that contains a AJAX post. I'm trying to refer to the class members from within the post function using this but it doesn't seem to be working.

For example, from this:

function Classy() {

  this.goal = 0;

  $.post(   
    "class/initial.php",
    function(back) {                
        this.goal = back.goal;  
  }, "json");       

  this.SampleFunction = function() {
    alert(this.goal);   
  }

}

tester = new Classy();
tester.SampleFunction();

The alert box outputs a value of 0, even though this is definitely not what is coming back from the php file. I think the issue is I need something other than this to refer to the parent class. Anyone have any ideas?

Upvotes: 0

Views: 155

Answers (3)

gilly3
gilly3

Reputation: 91487

In event handlers, this refers to the object which fired the event. An AJAX success callback is really an event handler for the XMLHttpRequest object that does the work, so in this case, this refers to the XMLHttpRequest object (well, actually a jqXHR object). To get a reference to your object, assign this to a variable that you can reference from within your event handler:

function Classy() {
    this.goal = 0;
    var that = this;
    $.post("class/initial.php", function(back) {                
        that.goal = back.goal;  
    }, "json");     
}

Upvotes: 0

user113716
user113716

Reputation: 322462

function Classy() {

    this.goal = 0;

     // jQuery.proxy returns a function
    $.post("class/initial.php", $.proxy(function (back) {
        this.goal = back.goal;
    }, this), "json");
      // ^-------- is manually set in your handler

    this.SampleFunction = function () {
        alert(this.goal);
    }
}

You can use the jQuery.proxy()[docs] method to ensure the proper this value.


Another possibility is to use the long form jQuery.ajax()[docs] method, where you can set the context: parameter to give you the desired this value.

function Classy() {

    this.goal = 0;

    $.ajax({
        type:'POST',
        url:"class/initial.php", 
        dataType: 'json',
        context: this, // <--set the context of the callbacks
        success: function (back) {
            this.goal = back.goal;
        }
    });    
    this.SampleFunction = function () {
        alert(this.goal);
    }
}

Upvotes: 2

Craig Stuntz
Craig Stuntz

Reputation: 126547

this means something different inside the anonymous function which jQuery invokes in a callback. So just capture it first:

function Classy() {

  this.goal = 0;
  var $t = this;

  $.post(   
    "class/initial.php",
    function(back) {                
        $t.goal = back.goal;  
  }, "json");       

  this.SampleFunction = function() {
    alert(this.goal);   
  }
}

Upvotes: 2

Related Questions