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!