简体   繁体   中英

Can you import a variable declared inside a function while using OOP in javascript?

I am using ES6 classes and modules. I have a method in my location module that gets the user's latitude and longitude. I in turn want to import them to another module where I will interact with the openWeatherApi.

Here are my code samples

This my location module,that holds the location class

class Location {
  constructor() {
    this.getPosition();
  }

  getPosition() {
    navigator.geolocation.getCurrentPosition(this.getCoords, this.error);
  }

  getCoords(position) {
    const {latitude, longitude} = position.coords;
    console.log(latitude, longitude);
  }

  error(err) {
    console.error(err);
  }
}


export { Location };

here is my module where I will interact with the openweatherApi

import { Location } from "./location.js";

const userLocation = new Location();

console.log(userLocation.latitude);
console.log(userLocation.longitude);

Please how can I access the longitude and latitude variable declared in the location module, in my new module.

You can't access by this way the longitude and latitude. Cause both are local varibles.

You have to define both variables as member variables.

constructor() {
    this.longitude = undefined;
    this.latitude = undefined;
    this.getPosition();
}

getCoords(position) {
    this.longitude = position.coords.longitude ;
    this.latitude = position.coords.latitude ;
    console.log(this.latitude, this.longitude);
}

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