Ivan Seidel Ivan Seidel - 5 months ago 11
Javascript Question

How to access object property from inside class function

one of my classes in Javascript needs to be "updated" with Json sometimes. I have always done a function, that updates the array of data, given an id, but now i wanted to do it more encapsulated (Function update, inside the class).

What i made:

function File(data){
this.data = data;

this.update = function (callback){
var set = function(ajaxData){
this.data = ajaxData.PcbFile;
}
getPcbFile(data.id, function(ajaxData){
set(ajaxData);
callback();
});
};
}


But,
this.data = ajaxData.PcbFile;
doesen't work... My object still with the last data set, and not the updated one. The function SET, i created as another attempt to set the data.

There is no problem on the ajax, since i debuged the ajaxData, and it's ok (when i update).

So, how do i really access the object property
data
from an inside function?

(sorry for my english...)

Answer

I learned this the hard way, you have to be careful with this. It always refers to the this in the current scope, not it's containing object. Whenever you wrap something in function() { ... }, this becomes of a different scope. In your case, duplicate the object to a local variable and manipulate it's .data property.

function File(data){
    this.data = data;
    var file = this; //call the variable whatever you want
    this.update = function (callback){
        var set = function(ajaxData){
            file.data = ajaxData.PcbFile;
        }
        getPcbFile(data.id, function(ajaxData){
            set(ajaxData);
            callback();
        });
    };
}
Comments