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...)
I learned this the hard way, you have to be careful with
this
. It always refers to thethis
in the current scope, not it's containing object. Whenever you wrap something infunction() { ... }
,this
becomes of a different scope. In your case, duplicate the object to a local variable and manipulate it's.data
property.Try this:
The value of
this
within a function depends on how that function is called. E.g., when you use the "dot" notation,someObj.someMethod()
then withinsomeMethod()
you'd havethis
set tosomeObj
. You can explicitly setthis
to some other object using the.apply()
or.call()
methods. Otherwise if you call a function as withset(ajaxData)
thenthis
will be the global object (window
).By keeping a reference to
this
outside your function (I prefer the variable nameself
for this purpose) you can reference it inside your function.Cache
this
so you can refer to it in the same context some place else: