Py学习  »  Jquery

如何使jquery构造函数属性全局可见

Java_code • 4 年前 • 192 次点击  

我正在尝试使用jquery的标准navigator.geolocation属性获取位置坐标变量,以便稍后在代码中使用该值:


$(document).ready(function(){

    $.getlocation = function(){
          navigator.geolocation.getCurrentPosition($.getPosition,$.error);
    }

    $.getVariables = function(lat,lon){
          this.lat = lat; // i want these to be visible
          this.lon = lon;
    }

    $.getPosition= function(position){
          console.log("latitude:" +position.coords.latitude+ " longitude: "+position.coords.longitude);
          //this function will be executed once position is determined.


    $.getVariables(position.coords.latitude,position.coords.longitude);
    }

    $.error = function(){alert("error");}

    $.getlocation(); // outputs correctly

    setTimeout(()=>{console.log(this.lat)},5000); // undefined

});

我希望得到位置输出,但是我得到了 undefined console.log(this.lat) ,我在vanilla javascript中尝试过,它运行得很好,下面是javascript代码:

function locateMe() {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getPosition, error);
    } else {

        alert("connection problem");
    }
}

let vars = function(lat, lon) {
    this.lat = lat;
    this.lon = lon;
}

let getPosition = function(position) {
    vars(position.coords.latitude, position.coords.loongitude);
}


let error = function(msg) {
    console.log("problem");
}

locateMe();

setTimeout(() => { console.log(this.lat); }, 5000); //correct output

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46708
 
192 次点击  
文章 [ 1 ]  |  最新文章 4 年前
ItsPete
Reply   •   1 楼
ItsPete    4 年前

我可以得到 this.lat 如果我换了工作 getVariables 致:

$.getVariables = function(lat,lon){
    document.lat = lat;
    document.lon = lon;
}

看来这两个 this 在这两种方法中,对象可以引用不同的东西。