I am currently learning OOP in JavaScript. I'm refactoring an app and I have a problem.
I have created a Class "Weather"
class Weather {
constructor({longitude, latitude} = {}) {
this.longitude = longitude;
this.latitude = latitude;
this.options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
}
getLongitude(){
return this.longitude;
}
setLongitude(longitude){
this.longitude = longitude;
}
getLatitude(){
return this.latitude;
}
setLatitude(latitude){
this.latitude = latitude;
}
getLocation() {
if (Modernizr.geolocation) {
//if locatin is enabled, show position in button
navigator.geolocation.getCurrentPosition(this.success, this.fail, this.options);
} else {
alert("Sorry, you browser doesn't have geolocation");
}
}
success(position){
let pos = position.coords;
console.log('Your actual position is :');
console.log(`Latitude : ${pos.latitude}`);
console.log(`Longitude: ${pos.longitude}`);
console.log(`More or less ${position.coords.accuracy} meters.`);
this.setLongitude(pos.longitude); // <== Doesn't work
this.setLatitude(pos.latitude); // <== Doesn't work
}
fail(){
console.log('User refused to give position');
}
}
Everything works, I can retrieve longitude and latitude like that
let City = new Weather();
City.getLocation(); //will call getLocation and on success, it will console.log the longitude and latitude
My problem is that I can update the value of my object. When I create my object, the constuctor defines a longitude and latitude if they are passed as argument. However, in the success method, I cannot reassign value of the object.
Is there any solution ?
thisvariable, common practice is to put avar self = this;at the top, and use self where you want the class this reference.success(position){bla bla}.bind(this);