在 JavaScript 类 中引用静态变量

Referencing static variables in JavaScript classes

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

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

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

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)

这是我的解决方案,将静态 class 变量称为 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);
    }
}

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

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

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