2012-12-31 23 views
0

嘿所以我开始选择Javascript,并且遇到了一些对象的问题。 我正在尝试创建一个需要多个边的形状类。使用这些边,它会创建更多特征,以便存储点的位置坐标。 我现在所拥有的是一个正在考虑大小的类,我想使用for循环来创建存储位置的“属性”。仅仅为了学习目的,我将它们设置为0,以查看是否可以做到这一点。任何澄清对象将不胜感激。试图通过for循环声明一个对象的多个特征

function Shape(size) { 
    this.size = size 
    for(var i=0; i<size; i++){ //tries to create the properties 
     //this[i].posX: 0; 
     //this[i].posY = 0; 
    } 
} 

理想情况下,我想这样是访问他们在这个类型的格式:

var triangle = new Shape(3); 
triangle[0].posX = 100; // So essentially I could set this to 100, the integer in the [] would represent a side. 
triangle[0].posY = 100; // etc ... for the rest of the sides 

的感谢!

回答

0

由于形状可以具有可变数量的面,我会建议创建点的阵列作为Shape类的属性。

function Shape(size) { 
    this.size = size; 
    this.point = new Array();//stores an Array of Points 
    for(var i=0; i<size; i++){ 
     this.point[i] = new Point(0, 0); 
    } 
} 

function Point(x, y){ 
    this.posX = x || 0; 
    this.posY = y || 0; 
}; 

这样,您就可以创建下面的代码一个三角形:

// Creates a triangle with the points at (100, 100), (0, 0), and (0, 0) 
var triangle = new Shape(3); 
triangle.point[0].posX = 100; 
triangle.point[0].posY = 100; 

我希望这有助于。

+0

是的,我结束了思考数组,但我觉得有可能是一个更简单的方法,然后创建一个新的对象数组。谢谢 – wzsun

0

我很难理解你的问题/问题是什么。但在我看来,Javascript并不像C#或VB.NET或类似语言那样真正支持'属性'。您的解决方案使用两种格式的方法:
1.设置值的方法。
2.返回值的方法。
所以,你的类应该有一些像这样的4种方法:

setPosX(var posx) 
getPosX() 
setPosY(var posy) 
getPosY() 

然后你只需创建一个数组:

var triangles = new Array(); 

并通过给你的值循环:

function Shape(size) { 
     for(var i=0; i<size; i++){ //tries to create the properties 
      triangles[i].setPosX(0); // or any other value 
      triangles[i].setPosY(0); 
     } 
    } 

另请注意,此功能将在类结构之外。 希望这有助于;)

0

试试下面的代码。那是你要的吗?

function Shape(size) { 
    var arr = new Array(size); 

    for(var i=0; i <size; i++){ //tries to create the properties 
     arr[i] = { 
      posX: 0, 
      posY: 0 
     }; 
     //arr[i] = {}; 
     //arr[i].posX = 0; 
     //arr[i].posY = 0; 
    } 

    return arr; 
} 

现在你可以这样做:

var triangle = new Shape(3); 
triangle[0].posX = 100; // So essentially I could set this to 100, the integer in the [] would represent a side. 
triangle[0].posY = 100; // etc ... for the rest of the sides 
相关问题