1

I have the following C++ struct which I want to create as faithfully as possible in Javascript:

struct Vertex
{
   float coords[4];
   float colors[4];
};

So I did the following:

function Vertex(coords, colors)
{
   this.coords = [];
   this.colors = [];
}

Now, the following works to create a Vertex instance:

var oneVertex = new Vertex();
oneVertex.coords = [20.0, 20.0, 0.0, 1.0];
oneVertex.colors = [0.0, 0.0, 0.0, 1.0];

but the following (slicker?) doesn't:

var oneVertex = new Vertex([20.0, 20.0, 0.0, 1.0], 
                            [0.0, 0.0, 0.0, 1.0]);

Why? I am new to Javascript and what little I have read suggests it should be ok. Obviously not. It would be helpful to understand what I am missing. Thanks.

2
  • you are passing the arrays to the function, but you are setting the coords and colors to empty and not using the data you pass in Commented Apr 17, 2016 at 20:48
  • There's a strong distinction between function parameters and object properties. Learning language basics is always a good start. Commented Apr 17, 2016 at 20:48

2 Answers 2

5

you need to use the arguments passed in to the function for it to work, as:

function Vertex(coords, colors)
{
   this.coords = coords || [];
   this.colors = colors || [];
}
Sign up to request clarification or add additional context in comments.

Comments

1

You're constructor should initialize the properties:

function Vertex(coords, colors)
{
   this.coords = coords;
   this.colors = colors;
}

var oneVertex = new Vertex([20.0, 20.0, 0.0, 1.0], 
                            [0.0, 0.0, 0.0, 1.0]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.