Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 955
Arnold Avatar asked Dec 07 '13 19:12

Arnold


People also ask

How do you call a function inside a callback function?

You need to use the . call() or . apply() methods on the callback to specify the context which the method is called upon. The callback method remote_submit does not know what this will be anymore and thus when it calls the callback methods they're executed like normal functions not on an object.

Can a callback function call another function?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

How do you pass a callback function in JavaScript?

Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn); Above is an example of a callback variable in JavaScript function.

How do I call multiple callback functions in JavaScript?

Just pass down the callbacks from the first function and execute each one, passing down the rest.


1 Answers

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();
   });
};
like image 86
Bill Criswell Avatar answered Oct 02 '22 23:10

Bill Criswell