3

My use case is the geocoder.geocode api from the google map library. I'm using it to convert a given user address to a latitude/longitude coordinate for use with another google map api.

This api executes the callback when it is finished searching the input address. From within the callback, I am trying to access a member of my class by using the this keyword.

I understand this, from within a closure refers to a different context than the class the closure sits in - so at the top of the method I've created variable and cached off the this instance, by doing var self = this.

This works, but is it the accepted approach? I am using ES6 if that matters.

mariocatch
  • 8,305
  • 8
  • 50
  • 71

1 Answers1

2

var self = this; was the preferred solution in ES5 and before. I followed the style where no matter what, the first line would always be var self = this;. It prevented silly mistakes.

In ES6, we have arrow functions. These are anonymous functions that lexically bind the this value. It means that it does not have its own this, that regular Javascript functions have. With ES6, you can just do this:

var myFunction = function(){ 
    this.someValue = 1;
    someFunction((callbackResult) => { // ARROW FUNCTION
        this.someValue = 2;
    });
};

instead of this:

var myFunction = function(){ 
    var self = this;

    self.someValue = 1;
    someFunction(function(callbackResult){
        self.someValue = 2;
    });
};
Oliver
  • 3,981
  • 2
  • 21
  • 35