I'm writing an application in javascript and cannot figure it out how to access the variables declared in my function, inside this jquery parse. Inside I can access global variables, but I don't really want to create global vars for these values.
Basically I want to extract file names from an xml document in the simulationFiles
variable. I check if the node attribute is equal with the simName
and extract the two strings inside the xml elements, that part I think it's working.
How can I extract those xml elements and append them to local variables?
function CsvReader(simName) {
this.initFileName = "somepath";
this.eventsFileName = "somepath";
$(simulationFiles).find('simulation').each(function() {
if ($(this).attr("name") == simName) {
initFileName += $(this).find("init").text();
eventsFileName += $(this).find("events").text();
}
});
}
The
this
in theCsvReader
function is not the samethis
in theeach()
callback (where instead it is the current element in the iteration). To access the scope of the outer function within the callback, we need to be able to reference it by another name, which you can define in the outer scope:The simplest change you can do to make it work is... Change your function in each from normal ( function() {}) to arrow function ( () => {} ) that will automatically take the context of the function in which it is defined.
I made a working demo (I changed it to use classes so it would work with HTML).