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

后端 未结 3 929
小蘑菇
小蘑菇 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:36

    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.

    0 讨论(0)
  • 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();
           }
        });
    }
    
    0 讨论(0)
  • 2020-12-17 02:43

    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();
           }
        });
    }   
    
    0 讨论(0)
提交回复
热议问题