Javascript 公开配音

Javascript oop dubt

我在下面的代码中制作了这两个 class,但我不确定我是否以正确的 oop 方式制作了它。我把几何 class 和顶点做成两个不同的 class 是不是很好,或者他们可以是一对父子?另一个问题是当我调用 geometry show 方法时它 returns 我未定义。

//////////////////////////////////////////
// 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
}

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

看起来不错,我看不出任何常见错误。

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

取决于您的需要。它本身没有任何问题,但如果您告诉我们您的用例,我们可能会找到不同的解决方案。

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

不,不应该有任何继承。他们之间没有is-a relationship。它们应该是不同的 类,一个使用另一个。

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

是的,因为它没有 return 任何东西。它从调用 Vertice show() 调用中获得的所有那些字符串都将被丢弃。看起来你想要像

这样的东西
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!
}