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?
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.
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.
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.
Just pass down the callbacks from the first function and execute each one, passing down the rest.
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();
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With