简体   繁体   中英

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}`;
  }
lat = latitude; // Hoping to modify myLatitude here

Here, you assign the variable name lat to the object latitude, but you do not modify this.myLatitude .

I think you want to do:

this.myLatitude = latitude;

You have to read a bit about variable scope and assignation: you have to understand the difference between a variable/name and the object it points to.

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;
  ...
}

You don't need this sentence

lat = latitude;

Instead of that

Try this:

myLatitude=latitude;

You could define property myLatitude in a ES6 class constructor and in your concise method activate you could get myLatitude property and change its value using this keyword.

Quick example:

 let Welcome = class Welcome { constructor(height, width) { this.myLatitude = 0; } activate() { this.myLatitude = '1'; // assign a new value alert('this.myLatitude is: ' + this.myLatitude); } }; let myWelcome = new Welcome(); myWelcome.activate(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM