Function constructor and function within function

2

I'm stuck on a JavaScript question that asks for the distance between two points using that formula d (p1, p2) = sqrt ((x1-x2) ² + (y1-y2) ²). The problem is that you ask:

"Rewrite exercise 5 using objects created from a" Point "constructor function, the created point object must contain two properties ages equivalent to the values of x and y and a function that receives another object point and returns the distance between them. "

Here's my code:

function Ponto(x,y){
  this.pontox = x;
  this.pontoy = y;
  this.calcula = function(p){
    aux1 = Math.pow(Ponto.x - p.x,2);
    aux2 = Math.pow(Ponto.y - p.y, 2);
    result = Math.sqrt(aux1+aux2,2);
    console.log(result);        
  }
}
ponto1 = new Ponto(0,0);
ponto2 = new Ponto(1,1);
ponto1.calcula(ponto2);

Only the code only returns NaN , not the result in float , as I would like. I have tried to pass the values to float , but I could not get results, so how do you return the value in float ?     

asked by anonymous 24.03.2016 / 16:58

1 answer

2

Epiphany, a tip, avoid putting the statement and functions in the "constructor" class, instead use prototype.

no longer can you access the properties of the current object using this , then instead of Ponto.x , use this.pontox , or rather rename it to this.x only ... refinement is Ponto.pontox .

var Ponto = function (x,y){
  this.x = x;
  this.y = y;
}

Ponto.prototype.calcula = function (pontoB) {
  var calc = {};
  calc.x = Math.pow(this.x - pontoB.x, 2);
  calc.y = Math.pow(this.y - pontoB.y, 2);
  return Math.sqrt(calc.x + calc.y, 2);
}

ponto1 = new Ponto(0,0);
ponto2 = new Ponto(1,1);

var distancia = ponto1.calcula(ponto2);
console.log(distancia);
    
24.03.2016 / 17:16