Construction function and function within function

Asked

Viewed 371 times

2

I’m pressing 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 you ask:

"Rewrite exercise 5 using objects created from a "Point" constructor function, the created point object must contain two propri- equivalent values of x and y and a function receiving another point object and returns the distance between them."

Here is 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, and not the result in float, as I would like. I have already tried to pass the values to float, but I didn’t get results, so how to make the function return the value in float?

  • I noticed a bit of confusion regarding the access of variables within the "class", in that reply the scopes of the variables and the form of access are explained.

1 answer

2

Epifanio, a hint, avoid putting the declaration and functions in the class "constructor", instead make use of the prototype.

in the further you can access the properties of the current object using the this, then in place of Ponto.x, use this.pontox, or rather, rename it to this.x just... tuning is kind of reductive 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);

  • 1

    cool, using the .prototype the code gets cleaner even, there is some other reason that encourage the use?

  • 2

    @Prototype sanction is more efficient in both memory and CPU usage (including this was one of the reasons for its inclusion in Javascript). In the original example of the question the function calcula is created every time a Ponto is instantiated, already in this example with prototype calcula is defined only once, right in the statement, and all instances share the same implementation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.