2017-01-16 106 views
0

我正在將一個可用的JS解決方案重新實現到Typescript中。 我有一個在緯度和經度上都有地理位置的對象數組。Typescript將其綁定到數組排序

我想根據他們的距離排序他們到一個特定的位置,currentLocation

我想存儲currentLocation作爲一個私人屬性,並在排序函數內訪問它。但是,在執行this.currentLocation時,這在compare中未定義。我試過compare.bind(this),但沒有成功。 this is not defined

任何想法如何解決這個問題?我用全局變量在JS中解決了這個問題,但這並不優雅。 sortByDistance是一種對象方法。

sortByDistance() { 

     this.currentPosition = Leaflet.latLng(this._currentLatLng[0], this._currentLatLng[1]); 

     function compare(a, b) { 
     let p1 = Leaflet.latLng(a.lat, a.lng); 
     let p2 = Leaflet.latLng(b.lat, b.lng); 

     if (p1.distanceTo(this.currentPosition) < p2.distanceTo(this.currentPosition)) 
      return -1; 
     else if (p1.distanceTo(this.currentPosition) > p2.distanceTo(this.currentPosition)) 
      return 1; 
     return 0; 
     } 
     compare.bind(this); 
     this.sorted = this.objects.sort(compare); 

    } 

回答

1

compare.bind(this)返回一個新函數。嘗試this.objects.sort(compare.bind(this));

+0

謝謝,就是這樣。 –

2

您可以更改

function compare(a, b) { 
     let p1 = Leaflet.latLng(a.lat, a.lng); 
     let p2 = Leaflet.latLng(b.lat, b.lng); 

     if (p1.distanceTo(this.currentPosition) < p2.distanceTo(this.currentPosition)) 
      return -1; 
     else if (p1.distanceTo(this.currentPosition) > p2.distanceTo(this.currentPosition)) 
      return 1; 
     return 0; 
     } 

compare = (a, b)=>{ 
    let p1 = Leaflet.latLng(a.lat, a.lng); 
    let p2 = Leaflet.latLng(b.lat, b.lng); 

    if (p1.distanceTo(this.currentPosition) < p2.distanceTo(this.currentPosition)) 
     return -1; 
    else if (p1.distanceTo(this.currentPosition) > p2.distanceTo(this.currentPosition)) 
     return 1; 
    return 0; 
} 

使this將在詞彙範圍

+0

它應該像'比較=(a.b)=> {};' –

+0

@suraj謝謝,修正。 – echonax

1

bind作品略有不同:

const boundCompare = compare.bind(this); 
this.sorted = this.objects.sort(boundCompare); 
+0

我很好奇 - 爲什麼要在Typescript中添加'const'而不是'let'?一個'const'函數確保不能重寫? –

+0

我更喜歡在'let'上儘可能使用'const' - 因爲我不能重新使用這個變量。當我查看用'const'定義的東西時,我知道該變量不會被用於任何其他目的 - 或更改值 - 用於該函數的運行。這是'函數式編程'的基本部分http://eloquentjavascript.net/1st_edition/chapter6.html –