簡體   English   中英

如何從同一對象中的不同函數調用對象定義的函數?

[英]How to call a object defined function from the a different function in the same object?

我正在使用javascript為小型個人項目制作自定義對象,這些對象通常可用於平板電腦(但也適用於筆記本電腦)。 該對象處理Google地圖,gps跟蹤以及其他過程。 在對象內部,我定義了從對象外部調用的couple函數( enableGps, disableGps )。 在enableGps內部,我開始跟蹤,同時使用外部error_handler和內部對象函數( this.handleGps )處理gps數據(緯度,經度,准確性等)。 this.handleGps我嘗試調用this.updateGpsMarker函數以更新地圖上的實際標記,但會引發異常。

未捕獲的TypeError:對象[object Window]沒有方法'updateGpsMarker'

我怎么能叫this.updateGpsMarkerthis.handleGps 請注意,我需要this.updateGpsMarker作為從外部調用的函數(詳細說明),我將拋出代碼以使其更加清楚我要做什么。

function RouteAssistant(mapCanvas, mapOptions)
{
    // Google mapping and geocoding
    this.map = new google.maps.Map(mapCanvas, mapOptions);
    this.geo = new google.maps.Geocoder();
    this.gpsMarker = null;

    this.updateGpsMarker = function(lat, lon)
    {
        console.log("Updating GPS marker");
        if (this.gpsMarker == null)
        {
            console.log("GPS Marker not created. Creating GPS marker at " + lat + "," + lon);
            this.gpsMarker = new google.maps.Marker(
            {
                position: new google.maps.LatLng(lat,lon),
                map: this.map,
                title: "I am here!"
            });
            this.map.setCenter(new google.maps.LatLng(lat,lon));
        }
        else
        {
            console.log("GPS Marker created. Updating GPS marker to " + lat + "," + lon);
            this.gpsMarker.setPosition(new google.maps.LatLng(lat,lon));
        }
    }

    // GPS and tracking
    this.gpsProcess = null;
    this.enableGps = function (handle_errors)
    {
        if (this.gpsProcess == null) {
            console.log("Enabling GPS");
            this.gpsProcess = navigator.geolocation.watchPosition(this.handleGps, handle_errors);
        }
    };
    this.disableGps = function()
    {
        if (this.gpsProcess != null)
        {
            console.log("Disabling GPS");
            navigator.geolocation.clearWatch(this.gpsProcess);
            this.gpsProcess = null;
        }
    };
    this.handleGps = function(position)
    {
        this.updateGpsMarker(position.coords.latitude, position.coords.longitude);
    }
}

可能您可以使用諸如顯示模數模式之類的東西來創建一個干凈的對象,然后將所有功能放入其中。

 var routeAssistant = function(mapCanvas, mapOptions) {

     var map = new google.maps.Map(mapCanvas, mapOptions).
     updateGpsMarker = function(lat, long) {
         //You can directly access 'map' here.
     };
     return {
      updateGpsMarker : updateGpsMarker
     }; 
 };

然后,您可以通過執行此操作

  var myObject = new routeAssistant(mapCanvas, mapOptions);
  myObject.updateGpsMarker(latitude,longtitude);   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM