如何在另一个函数的回调中调用JavaScript函数? [英] How can I call a JavaScript function in a callback of another function?

查看:69
本文介绍了如何在另一个函数的回调中调用JavaScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

function User(){
   this.nickname='nickname';
} 
User.prototype.save=function(){
   dosomething();
};
User.prototype.add=function(){
   navigator.geolocation.getCurrentPosition(function(positon){
        this.save();
   });
};

this.save()错误,我想在另一个回调中调用 save()。我发现这不是指向用户,如何正确调用 save()

but this.save() is wrong, I want to call save() in another callback. I find this isn't pointing to the User, how can I call save() correctly?

推荐答案

这个里面的 getCurrentLocation 可能不是你想象的那样。尝试:

this inside getCurrentLocation probably isn't what you think it is. Try:

User.prototype.add=function(){
  var self = this;
   navigator.geolocation.getCurrentPosition(function(positon){
        self.save();
   });
};

这篇关于如何在另一个函数的回调中调用JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆