i have been learning javascript for a few days. and im having problems with the sintaxis and the semantics of my programs, i can make run this simple problem. i dont know whats wrong with it
//2. **Distance between two points**. Create a
//function that calculate the distance between two points
//(every point have two coordinates: x, y). _HINT: Your function
//Should receive four parameters_.
function Point(x,y,x1,y1){
this.x = x;
this.y = y;
this.x1 = x1;
this.y1 = y1;
this.distanceTo = function (point)
{
var distance = Math.sqrt((Math.pow(this.x1-this.x,2))+(Math.pow(this.y1-this.y,2)))
return distance;
};
}
var newPoint = new Point (10,100);
var nextPoint = new Point (25,5);
console.log(newPoint.distanceTo(nextPoint));
Try This instead:
function Point(x,y){
this.x = x;
this.y = y;
this.distanceTo = function (point)
{
var distance = Math.sqrt((Math.pow(point.x-this.x,2))+(Math.pow(point.y-this.y,2)))
return distance;
};
}
var newPoint = new Point (10,100);
var nextPoint = new Point (20,25);
console.log(newPoint.distanceTo(nextPoint))
In your distanceTo function you needed to refer to point.x and point.y instead as those are the points of nextPoint.
Hope this Helped :3
Point constructor should have just two arguments x and y. And distanceTo should use the x and y of this point ant the other point (the one passed as parametter).
function Point(x, y){ // only x and y
this.x = x;
this.y = y;
this.distanceTo = function (point)
{
var dx = this.x - point.x; // delta x
var dy = this.y - point.y; // delta y
var dist = Math.sqrt(dx * dx + dy * dy); // distance
return dist;
};
}
var newPoint = new Point (10,100);
var nextPoint = new Point (25,5);
console.log(newPoint.distanceTo(nextPoint));
Note: Since all Point instances have the exact same distanceTo function, it is better to define it on the prototype instead of redefining it for each instance which will only increase creation time and waste a lot of ressources.
This is better:
function Point(x, y){ // only x and y
this.x = x;
this.y = y;
}
Point.prototype.distanceTo = function (point)
{
var dx = this.x - point.x; // delta x
var dy = this.y - point.y; // delta y
var dist = Math.sqrt(dx * dx + dy * dy); // distance
return dist;
};
var newPoint = new Point (10,100);
var nextPoint = new Point (25,5);
console.log(newPoint.distanceTo(nextPoint));
More about prototpes here!
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