Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  55] [ 2]  / answers: 1 / hits: 15671  / 12 Years ago, mon, august 6, 2012, 12:00:00

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...)


More From » class

 Answers
23

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();
});
};
}

[#83833] Saturday, August 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devinjadong

Total Points: 711
Total Questions: 117
Total Answers: 100

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
devinjadong questions
Thu, Feb 17, 22, 00:00, 2 Years ago
Wed, Dec 8, 21, 00:00, 2 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Fri, Oct 18, 19, 00:00, 5 Years ago
;