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...)
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .
You cannot. Property keys are unique.
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();
});
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With