【发布时间】:2019-03-18 11:43:27
【问题描述】:
我发现大多数类似下面的代码,它们可能在 javascript 中工作,但我无法让它在 Typescript 中工作。
//javascript version
navigator.geolocation.getCurrentPosition( function(position){
ShowLocation( position, variable );
});
function ShowLocation(position, variable){
console.log(position, variable);
}
//what I've tried on typescript
map:any="test";
private GetCurrentLocation(): void {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
/*something goes wrong here*/
this.ShowLocation(position, this.map);
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
public ShowLocation(position: any, map: any): void {
console.log(position, map);
//do something with the position and map parameters
}
core.js:1448 ERROR TypeError: Cannot read property 'ShowLocation' of null
我不知道如何在打字稿中完成这项工作。我不明白为什么会出现这个错误。
编辑:在可能的重复链接中找到了解决方案,必须对“this”使用绑定,谢谢!
//working code
//what I've tried on typescript
map:any="test";
private GetCurrentLocation(): void {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
this.ShowLocation(position, this.map);
}.bind(this));
} else {
alert("Geolocation is not supported by this browser.");
}
}
public ShowLocation(position: any, map: any): void {
console.log(position, map);
//do something with the position and map parameters
}
【问题讨论】:
标签: typescript navigator