[英]Typescript bind this to array sort
I am re-implementing a working JS solution into Typescript. 我正在Typescript中重新实现一个有效的JS解决方案。 I have an array of objects that have a Geolocation in latitude and longitudes.
我有一组对象,这些对象在纬度和经度上都有一个地理位置。
I want to sort them by their distance to one particular location, currentLocation
. 我想按它们到一个特定位置
currentLocation
的距离对它们进行排序。
I would like to store currentLocation
as a private attribute and access it within the sort function. 我想将
currentLocation
存储为私有属性,并在sort函数中访问它。 However, when doing this.currentLocation
, this remains undefined in compare
. 但是,在执行
this.currentLocation
,在compare
仍未定义。 I tried compare.bind(this)
, but no success. 我尝试了
compare.bind(this)
,但是没有成功。 this is not defined
. this is not defined
。
Any ideas how to solve this problem? 任何想法如何解决这个问题? I solved it in JS with global variables, but that's not elegant.
我用全局变量在JS中解决了这个问题,但这并不完美。
sortByDistance
is an object method. 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);
}
You can change 你可以改变
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;
}
with 与
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;
}
so that this
will be in lexical scope 这样
this
将在词汇范围内
compare.bind(this)
returns a new function. compare.bind(this)
返回一个新函数。 Try this.objects.sort(compare.bind(this));
试试
this.objects.sort(compare.bind(this));
bind
works slightly differently: bind
工作原理略有不同:
const boundCompare = compare.bind(this);
this.sorted = this.objects.sort(boundCompare);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.