javascript - 调用javascript函数时变量为空

标签 javascript

我有一个如下的函数。

我正在尝试调用它

var testVar =  new genericYiiLocation();
console.log(testVar.getLongitude());

但是,我的 this.getLongitude() 总是有一个空的 this.longitude。

我已检查 this.longitude 是否包含在locateSuccess(loc) 中设置时预期的值,看起来没问题。

如有任何指导,我们将不胜感激。

function genericYiiLocation() {

    console.log('genericYiiLocation: Creating location handler');

    this.longitude=  '';
    this.latitude=   '';
    this.accuracy=   '';

    if (Modernizr.geolocation) {
        console.log('genericYiiLocation: Location supported');
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(locateSuccess, locateFail);
        }
        else {
            alert('genericYiiLocation: Geolocation is not supported in your current browser.');
            return false;
        }
    } else {
        alert ('genericYiiLocation: no native location support');
        return false;
    }


     function locateSuccess(loc){
        console.log('genericYiiLocation: storing location data');
        this.longitude = loc.coords.longitude;
    }

    // Unsuccessful geolocation
    function locateFail(geoPositionError) {
        switch (geoPositionError.code) {
            case 0: // UNKNOWN_ERROR
                alert('An unknown error occurred, sorry');
                break;
            case 1: // PERMISSION_DENIED
                alert('Permission to use Geolocation was denied');
                break;
            case 2: // POSITION_UNAVAILABLE
                alert('Couldn\'t find you...');
                break;
            case 3: // TIMEOUT
                alert('The Geolocation request took too long and timed out');
                break;
            default:
        }
    }

    this.getLongitude = function(){
        console.log('long: '+this.longitude);
        return this.longitude;
    }
}

最佳答案

据我了解原因是:

this在你的回调中locateSuccessthis 不同在回调之外。为了实现你想要的,你可以绑定(bind)回调 localSuccess & locateFailthis使用Function.prototype.bind .

关于javascript - 调用javascript函数时变量为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300700/

相关文章:

javascript - boxslider 插件在 sitecore 预览模式下不工作

javascript - Raphael zoom 超出视野 - 添加滚动条

javascript - 无需测试即可检测脚本延迟支持

javascript - AngularJS - ForEach 不循环

javascript - 变量值改变不会延迟setTimeout?

javascript - 禁用 JQuery Ui 选项卡键盘导航

javascript - 如何将网络摄像头数据流式传输到服务器?

javascript - 如何添加 ngRoute 作为依赖项

javascript - 如何通过触发函数的元素的父div的类名获取另一个子元素

javascript - 重复密码验证不起作用