Arnold
Arnold

Reputation: 210

How can I call a JavaScript function in a callback of another function?

This is my code:

function User(){
   this.nickname='nickname';
} 
User.prototype.save=function(){
   dosomething();
};
User.prototype.add=function(){
   navigator.geolocation.getCurrentPosition(function(positon){
        this.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?

Upvotes: 5

Views: 102

Answers (1)

Bill Criswell
Bill Criswell

Reputation: 32921

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();
   });
};

Upvotes: 5

Related Questions