For my new project, I'm learning to work with objects in Javascript. So far, I've made a pretty big mess of it all and was hoping somebody could point out what's going wrong.
My main code:
var self = null; //to force a local 'self' variable from now on
var Person = function (firstName) {
this.firstName = firstName;
this.user_lat = 0;
this.user_long = 0;
this.user_accur = 0;
this.user_stable = 0;
};
Person.prototype.setCoordinates = function(lat, lng) {
this.user_lat = lat;
this.user_long = lng;
}
Person.prototype.fetchLocation = function() {
var self = this;
navigator.geolocation.getCurrentPosition(self.logPosition, function() { console.log("position fail") }, {enableHighAccuracy: true});
}
Person.prototype.logPosition = function(pos) { //saves coordinates in current person - object
this.setCoordinates(pos.coords.latitude, pos.coords.longitude);
}
index.php does the following:
var person = new Person("Lorre");
person.fetchLocation();
//do_stuff_with_location_in_object
However, the 'setcoordinates' function fails and gives an error:
Uncaught TypeError: undefined is not a function / main.js:40 / Person.logPosition
I'm pretty sure it's something stupid I'm doing wrong, but I've been struggling with "this"'es all evening now and I'm getting desperate... Hope any of you can see what's going wrong.
Thanks in advance!
var self = this;
is the beginning of maintaining the samethis
in a callback, but you have to add a second wrapper to use it, i.e.function (pos) { self.logPosition(pos); }
rather thanself.logPosition
.this.logPosition.bind(this)
works too, though. – Ry-♦ Dec 1 '14 at 19:45thank you
"answer". You might improve your answer and undelete it since every deleted answer counts against you. I could vote for undelete, but it was your decision I have to respect. – bummi Dec 1 '14 at 23:10