Tom celic Tom celic - 2 years ago 102
Javascript Question

Modifying class variable in function expression

I have some class variables which I want to modify in a function below but the value doesn't appear to stick.

export class Welcome {

myLatitude = 0; //I want to modify this inside activate()
myLongitude = 0;
myMarkers = [
{
latitude: -27.451673,
longitude: 153.043981
}
];

activate() {

var lat = this.myLatitude; // I thought this was getting a reference to myLatitude.

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){ //additional function
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;

lat = latitude; // Hoping to modify myLatitude here
...


However when I check the value of myLatitude again later, it still has a value of 0:

@computedFrom('myLatitude')
get myLat() {
console.log(this.myLatitude);
return `${this.myLatitude}`;
}

Answer Source

When you write var lat = this.myLatitude you create new independent variable. lat is not a link to this.myLatitude's value because it has a primitive one. Only objects in JavaScript are passed by reference.

So in your case you can save a link to the context var self = this before getCurrentPosition method call and after change the value in this way self.myLatitude = latitude.

Or you can use an arrow function:

navigator.geolocation.getCurrentPosition(position => {
  ...
  this.myLatitude = latitude;
  ...
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download