How can I access variables outside of current scope in javascript?

后端 未结 3 954
小蘑菇
小蘑菇 2020-12-17 02:02

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

3条回答
  •  情话喂你
    2020-12-17 02:41

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

提交回复
热议问题