0

I am currently in the process of learning Java Script, and am having an issue with using the .bind(this) method.

I have created a class called App() which will run my app. As a first step I am trying to create a variable in the class to store the latitude and longitude using the navigator.geolocation API.

When I define the variables in the method _getCurrentLocal() it works fine. When I try to define the latitude and longitude in the class, I get an error stating: "script.js:16 Uncaught TypeError: Cannot read properties of undefined (reading 'bind')", followed by: "script.js:31 Uncaught TypeError: Cannot set properties of undefined (setting 'latitude')"

My code is as follows:

class App {
  constructor() {
    this._getCurrentLocal().bind(this);
    this.latitude;
    this.longitude;
  }

  _getCurrentLocal() {
    //guard clause
    if (!navigator.geolocation) {
      console.log('no geo location');
      return;
    }
    //get geolocation
    navigator.geolocation.getCurrentPosition(
      function (position) {
        // const { latitude, longitude } = position.coords;
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        console.log('lat ', latitude, ' long ', longitude);
      },
      function () {
        prompt('Could not get your location');
      }
    );
  }
}

Any help would be greatly appreciated!

DntMesArnd
  • 115
  • 9
  • `_getCurrentLocal` doesn’t return anything, but it looks like you don’t mean to actually call the function in the constructor. Do you want to bind the callback function `function(position){`…`}`? That’s not `_getCurrentLocal`, that’s a completely different function. Why not use arrow functions here? What are `this.latitude;` and `this.longitude;` supposed to do? – Sebastian Simon Jan 12 '23 at 17:13
  • My thinking was the _currentLocal() method would use the navigator.geolocation API to determine the latitude and longitude of the user. From there i wanted them stored in the App class to be used by other methods (that I havent created yet) within that class. – DntMesArnd Jan 12 '23 at 17:17
  • What is `_currentLocal`? If you want to have a lexical `this` in the callback passed to `navigator.geolocation.getCurrentPosition`, simply replace the `function` by a callback function. If you want to have a lexical `this` in the `_getCurrentLocal` function, either use a public field whose value is an arrow function, or use `this._getCurrentLocal = this._getCurrentLocal.bind(this);` in the constructor. – Sebastian Simon Jan 12 '23 at 17:19

0 Answers0