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();
}
});
}
How do you call a variable inside a function in JavaScript? So the easiest way to make your variable accessible from outside the function is to first declare outside the function, then use it inside the function. var a; Parse.
No, You can't access let variables outside the block, if you really want to access, declare it outside, which is common scope.
Function and block scopes can be nested. In such a situation, with multiple nested scopes, a variable is accessible within its own scope or from inner scope. But outside of its scope, the variable is inaccessible.
Local variables cannot be accessed outside the function declaration. Global variable and local variable can have same name without affecting each other. JavaScript does not allow block level scope inside { } brackets.
The this
in the CsvReader
function is not the same this
in the each()
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:
function CsvReader(simName) {
this.initFileName = "somepath";
this.eventsFileName = "somepath";
var self = this; // reference to this in current scope
$(simulationFiles).find('simulation').each(function() {
if ($(this).attr("name") == simName) {
// access the variables using self instead of this
self.initFileName += $(this).find("init").text();
self.eventsFileName += $(this).find("events").text();
}
});
}
I made a working demo (I changed it to use classes so it would work with HTML).
function CsvReader(simName) {
this.initFileName = "somepath";
this.eventsFileName = "somepath";
var context = this;
$(simulationFiles).find('simulation').each(function() {
if ($(this).attr("name") == simName) {
context.initFileName += $(this).find("init").text();
context.eventsFileName += $(this).find("events").text();
}
});
}
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