[英]how to call 2 JavaScript methods in the same class?
我在这里有一些方法和更多方法的此类JS Bin
var Maps = (function () {
function Maps() {
}
Maps.prototype.getCoord = function () {
navigator.geolocation.getCurrentPosition(this.onPositionSuccess, this.onPositionError);
};
Maps.prototype.getWatchCoord = function () {
var options = { enableHighAccuracy: true, timeout: 3000 };
navigator.geolocation.watchPosition(this.onWatchSuccess, this.onWatchError, options);
};
Maps.prototype.onPositionSuccess = function (position) {
var pos = {
'latitude' : position.coords.latitude,
'longitude' : position.coords.longitude
};
console.log(pos);
};
Maps.prototype.onWatchSuccess = function (position) {
var pos = {
'latitude' : position.coords.latitude,
'longitude' : position.coords.longitude
};
console.log(pos);
};
Maps.prototype.onWatchError = function (error) {
console.log(error.code);
};
Maps.prototype.onPositionError = function (error) {
console.log(error.code);
};
return Maps;
})();
var maps = new Maps();
maps.getCoord();
我要尝试做的是,如果getCoord()
成功,则调用getWatchCoord()
并比较latitude
和longitude
。 如果它们相同,则不要运行getWatchCoord()
我试图在Maps类中尽可能做到这一点。
我已经尝试了几种方法,但似乎无法在getWatchCoord()
内调用getWatchCoord()
onPositionSuccess()
而不是我可以设置var x = navigator.geolocation.getCurrentPosition....
,然后return pos;
在成功回调内<-它不会返回任何东西
有任何想法吗?
您正在使用jQuery吗? 如果是这样,请执行以下操作:
var Maps = (function () {
function Maps() {
}
Maps.prototype.getCoord = function () {
navigator.geolocation.getCurrentPosition($.proxy(this.onPositionSuccess, this), $.proxy(this.onPositionError, this));
};
Maps.prototype.getWatchCoord = function () {
var options = { enableHighAccuracy: true, timeout: 3000 };
navigator.geolocation.watchPosition($.proxy(this.onWatchSuccess, this), $.proxy(this.onWatchError, this), options);
};
Maps.prototype.onPositionSuccess = function (position) {
var pos = {
'latitude' : position.coords.latitude,
'longitude' : position.coords.longitude
};
console.log(pos);
//call getWatchCoord
this.getWatchCoord();
};
Maps.prototype.onWatchSuccess = function (position) {
var pos = {
'latitude' : position.coords.latitude,
'longitude' : position.coords.longitude
};
console.log(pos);
};
Maps.prototype.onWatchError = function (error) {
console.log(error.code);
};
Maps.prototype.onPositionError = function (error) {
console.log(error.code);
};
return Maps;
})();
var maps = new Maps();
maps.getCoord();
如果您未传递具有正确范围“ this”的回调函数,则进入成功回调时,“ this”将是全局的,这就是我在上面使用$ .proxy的原因。 现在这未经测试,所以我不知道您在这里还有什么其他问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.