Javascript Noob calling for duty!
I would like to write the code for the following:
var p1 = new LatLon(userLat, userLon);
var p2 = new LatLon(destLat, destLon);
var dist = p1.distanceTo(p2);
which means I need to create a Javascript struct of sorts that will create a position and then also be able to take a second position as an argument. I DO NOT need the code to calculate the distance. I just need to figure out how to create the object and allow it to accept the arguments. Here is my pseudo code/ failed attempt:
function LatLon(userLat, userLon) {
var pos = {
'lat': userLat, 'lon': userLon, 'distanceTo': distanceBetweenTwoPos(pos, pos2);
}
return pos;
}
function distanceBetweenTwoPos(pos, pos2){
// here I will do my own calculations.
}
Any help on getting something similar to the above, yet functional?
Using the typical prototypal inheritance approach, it could look like this.
Inside the
LatLonconstructor, because you’re calling it withnew,thisis a reference to the object being constructed,returnstatement is needed; it’ll return the new object.Inside
distanceTo,thiswill be a reference to the object that called the method, so in your code, it would be a reference to thep1object.And of course
p2will be passed as an argument.