【问题标题】:Referencing static variables in JavaScript classes在 JavaScript 类中引用静态变量
【发布时间】:2019-09-04 14:46:37
【问题描述】:

在我的 React Native 应用程序中,GeoService 类是一组静态方法,其中包含两个声明的静态变量 idposition

如果我尝试使用 this 关键字从它自己的静态方法中引用静态类变量,它似乎会在不同的范围内创建一个新变量。如果没有 this 关键字,它会给出一个彻底的错误,即变量未解析。

static 关键字在 JS 中真的意味着什么有用的东西吗?在这里定义静态变量/方法的方法是什么?

CaptureView.js:

class CaptureView extends Component {
    constructor(props) {
        super(props);
        GeoService.start();
    }
    componentWillUnmount() {
        GeoService.stop();
    }
    onButtonPress() {
        Promise.all([this.cameraSrv.takePicture(), GeoService.getPosition()]).then(data => {
            let lat = data[1].lat; // PROBLEM HERE - Cannot read property 'lat' of undefined
            let log = data[1].lng;
        });
    }
}

GeoService.js:

import Logger from '../utils/Logger';

export default class GeoService {
    static _id = undefined;
    static _position = undefined;

    static start() {
        GeoService._getQuickPosition();
        GeoService._watchAccuratePosition();
    }

    static stop() {
        GeoService._clearWatch();
    }

    static getPosition() {
        return GeoService._position;
    }

    static _getQuickPosition() {
        navigator.geolocation.getCurrentPosition(
            GeoService._successCallback,
            GeoService._errorCallback,
            {enableHighAccuracy: false, timeout: 20000, maximumAge: 1000}
        );
    }

    static _watchAccuratePosition() {
        if (GeoService._id) {
            return;
        }

        GeoService._id = navigator.geolocation.watchPosition(
            GeoService._successCallback,
            GeoService._errorCallback,
            {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
        );
        Logger.info('GeoService watch started');
    }

    static _clearWatch() {
        navigator.geolocation.clearWatch(GeoService._id);
        delete GeoService._id;
        Logger.info('GeoService watch ended');
    }

    static _successCallback(position) {
        GeoService._position = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        Logger.info('GeoService new position: ' + JSON.stringify(GeoService._position));
    }

    static _errorCallback(error) {
        Logger.info('GeoService error: ' + error);
    }
}

React Native 控制台:

GeoService watch started
GeoService new position: {"lat":50.54822785298157,"lng":7.132454606843366}
GeoService new position: {"lat":50.54822785298157,"lng":7.132454606843366}
takePicture...
TypeError: Cannot read property 'lat' of undefined
    at CaptureView.js:187
    at tryCallOne (core.js:37)
    at core.js:123
    at JSTimers.js:298
    at _callTimer (JSTimers.js:152)
    at _callImmediatesPass (JSTimers.js:200)
    at Object.callImmediates (JSTimers.js:473)
    at MessageQueue.__callImmediates (MessageQueue.js:337)
    at MessageQueue.js:135
    at MessageQueue.__guard (MessageQueue.js:314)

【问题讨论】:

标签: javascript react-native oop static static-methods


【解决方案1】:

这是我的解决方案,将静态类变量称为GeoService.xxx

import Logger from '../utils/Logger';

export default class GeoService {
    static _id = undefined;
    static _position = undefined;

    static start() {
        GeoService._getQuickPosition();
        GeoService._watchAccuratePosition();
    }

    static stop() {
        GeoService._clearWatch();
    }

    static getPosition() {
        return GeoService._position;
    }

    static _getQuickPosition() {
        navigator.geolocation.getCurrentPosition(
            GeoService._successCallback,
            GeoService._errorCallback,
            {enableHighAccuracy: false, timeout: 20000, maximumAge: 1000}
        );
    }

    static _watchAccuratePosition() {
        if (GeoService._id) {
            return;
        }

        GeoService._id = navigator.geolocation.watchPosition(
            GeoService._successCallback,
            GeoService._errorCallback,
            {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
        );
        Logger.info('GeoService watch started');
    }

    static _clearWatch() {
        navigator.geolocation.clearWatch(GeoService._id);
        delete GeoService._id;
        Logger.info('GeoService watch ended');
    }

    static _successCallback(position) {
        GeoService._position = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        Logger.info('GeoService new position: ' + JSON.stringify(GeoService._position));
    }

    static _errorCallback(error) {
        Logger.info('GeoService error: ' + error);
    }
}

【讨论】:

    【解决方案2】:

    我认为您只能在实例中使用this,因为它必须引用实例化对象。 看起来您的解决方案是编写它的正确方法。

    我不确定,但在你的静态类中,我认为你不需要像这样嵌套函数调用:

        static getPosition() {
           return GeoService._position;
           // return _position; 
           // may work as well
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-05
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      • 2021-05-02
      • 2013-07-05
      • 2015-10-04
      相关资源
      最近更新 更多