0

So I'm having some issues while using openlayers gaining access to my fields within the inner scopes of function calls like so.

  method() {
    this.myField.on('click', function (args) {
      this.myFieldThatIsntInScope(evt.pixel, function (args) {
      });
    });
  }

The second field of this.myFieldThatIsntInScope is the one in question where it appears to be out of scope, and then any fields within that function are also out of scope.

Is there a way to scope these in, I tried assigning the various fields into variables within the code blocks parent level but seems to cause issues with the mapping object from ol that I'm using.

Munerz
  • 1,052
  • 1
  • 13
  • 26
  • 3
    Did you try arrow functions? `(args) => { this.myFieldThatIsntInScope(evt.pixel, (args) => { });` – Ashish Ranjan Jan 07 '19 at 09:42
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – David Walschots Jan 07 '19 at 09:55

1 Answers1

1

An arrow function does not have its own this; the this value of the enclosing lexical context is used i.e. Arrow functions follow the normal variable lookup rules.

So while searching for this which is not present in current scope they end up finding this from its enclosing scope . Thus, in the following code, the this within the function that is passed to myFieldThatIsntInScope has the same value as this in the lexically enclosing function.

  method() {
    this.myField.on('click',
      (args) => { this.myFieldThatIsntInScope(evt.pixel, (args) => { });
    });
  }
TheParam
  • 10,113
  • 4
  • 40
  • 51
  • 1
    everthing in detail over here https://medium.freecodecamp.org/learn-es6-the-dope-way-part-ii-arrow-functions-and-the-this-keyword-381ac7a32881 – TheParam Jan 07 '19 at 09:55