Giuseppe Matrizzi
Giuseppe Matrizzi

Reputation: 23

Javascript oop dubt

I made this two classes below in the code, and I am not sure if I made it in a right oop way. Is it good that I made geometry class and vertex like two distinct classes or maybe they can be one father and child? Another problem is when I call geometry show method and it returns me undefined.

//////////////////////////////////////////
// VERTICES
//////////////////////////////////////////


function Vertex(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}


Vertex.prototype.show = function () {
return this.x + ":" + this.y + ":" + this.z;
}


//////////////////////////////////////////
// GEOMETRY
//////////////////////////////////////////


function Geometry() {
this.vertices = [];                   
}


Geometry.prototype.push = function(v) {
this.vertices.push(v);
}


Geometry.prototype.show = function() {
for(var i = 0; i < this.getVertexCount(); i++){
     this.vertices[i].show();// undefined!
   }
}


Geometry.prototype.getVertexCount = function() {
return this.vertices.length;
}




/////TEST/////


function test() {



v = new Vertex(2,4,6);
console.log(v.show());
g = new Geometry();
g.push(v);
console.log(g.show()); //undefined
}

Upvotes: -1

Views: 41

Answers (1)

Bergi
Bergi

Reputation: 664620

I am not sure if I made it in a right oop way.

Seems fine, I can't see any common mistakes.

My doubt is for geometry class that has a vertice object field inside. Is it correct or the are better way to do it?

Depends on what you need. There's nothing inherently wrong with it, but if you told us your use case we might find a different solution.

Is it good that I made geometry class and vertex like two distinct classes or maybe they can be one father and child?

No, there should not be any inheritance. There is no is-a relationship between them. They should be distinct classes, one using the other.

Another problem is when I call geometry show method and it returns me undefined.

Yes, because it doesn't return anything. All those strings that it gets from the invocation of the Vertice show() calls are thrown away. It seems like you want something like

Geometry.prototype.show = function() {
   var result = "";
   for (var i = 0; i < this.getVertexCount(); i++) {
     if (i > 0)
       result += "\n";
     result += this.vertices[i].show();
   }
   return result; // not undefined!
}

Upvotes: 1

Related Questions