Hey so I started to pick up Javascript and I’m having a little bit of trouble with objects.
I’m trying to create a shape class that takes in a number of sides. Using these sides, it creates more characteristics so it can store the co-ordinates of the location of a point.
What I have right now is a class that is taking in the size, and I want to use a for loop to create the “properties” in which to store the positions. Just for learning purposes I’m setting them to 0, to see if it’s even possible to do this. Any clarification on objects would be appreciated.
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;
}
}
Ideally, I want to access them so it’s in this type of format:
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
thanks!
Since the shape can have a variable number of sides, I would recommend creating an Array of points as a property of the Shape class.
This way you can create a triangle with the following code:
I hope this helps.