Michael Pittino
Michael Pittino

Reputation: 2178

Access object property within a callback

I wrote the following code:

var Request = require('./request');

function Treasure(id) {
    Treasure.prototype.valid = false;
    Treasure.prototype.id = id;
    Treasure.prototype.contentLength = 0;
    Treasure.prototype.title = null;
    Treasure.prototype.seller = null;
    Treasure.prototype.buyer = null;
    Treasure.prototype.cost = 0;
}

Treasure.prototype.loadData = function() {
    EpvpRequest.treasureRequest(Treasure.prototype.id, function(data) {
        if (data.valid) {
            Treasure.prototype.valid = data.valid;
            Treasure.prototype.contentLength = data.contentLength;
            Treasure.prototype.title = data.title;
            Treasure.prototype.seller = data.seller;
            Treasure.prototype.buyer = data.buyer;
            Treasure.prototype.cost = data.cost;
        }
    });
}

module.exports = Treasure;

Please don't hit me, I just started learning javascript. I want ot access the properties of "Treasure"; but I can't use this, because I have a callback in the loadData function and this would refer to the function which called the callback - is that correct?

But it seems that I can't access the properties the way I tried with Treasure.prototype.property.

What is the correct way to to this?

Upvotes: 2

Views: 1901

Answers (1)

hugomg
hugomg

Reputation: 69964

First of all, you should be assigning instance variables in the constructor instead of assiginng to the prototype. The prototype is for methods and other things that will be shared by all Treasure instances.

function Treasure(id) {
    this.valid = false;
    this.id = id;
    this.contentLength = 0;
    this.title = null;
    this.seller = null;
    this.buyer = null;
    this.cost = 0;
}

As for your problem with this inside callbacks, the usual workaround is to store the value of this in a regular variable and then use that variable inside the callback.

Treasure.prototype.loadData = function() {
    // Nothing special about "that"
    // Its just a regular variable.
    var that = this;
    EpvpRequest.treasureRequest(that.id, function(data) {
        if (data.valid) {
            that.valid = data.valid;
            that.contentLength = data.contentLength;
            that.title = data.title;
            that.seller = data.seller;
            that.buyer = data.buyer;
            that.cost = data.cost;
        }
    });
}

Since this pattern comes up very often, some people choose to always use the same name for the "this-storage" variable. Some of the more popular names are self and that.

Upvotes: 4

Related Questions