Difference between "new createVector()" and "createVector()"

Hi

Can someone explain in simple terms what the difference is between createVector() and new createVector()?

Jason

Never seen the keyword new used on the p5’s method createVector():

AFAIK keyword new has no effect whatsoever on method createVector().

That’s what I thought. No effect. There is none that I could determine. I wrote it be accident and it worked, without complaint, so I became curious.

The keyword operator new creates an empty object and passes it to the invoked function becoming its internal keyword this.

By default that created new object is returned by the function unless the function explicitly returns another object.

The latter is what happens to method createVector().

It returns its own p5.Vector object and therefore the object created by new is simply discarded.

For more info on what happens when we use the keyword operator new go to its reference link below:

1 Like

Thank you! That explains why the results are the same then.

An important addendum! If we happen to be using instance mode in place of global mode:

The keyword new will actually change the behavior of method createVector() by forcing its internal keyword this to point to the plain object created by new.

Let’s say we have a parameter named p representing an instance of class p5.

When we invoke p.createVector(); its internal keyword this is gonna be equal to parameter p.

However if we use keyword new as in new p.createVector;, its internal this is gonna be equal to the object created by new instead of p!

And I’m suspicious that even in global mode new createVector; ends up replacing the global this by the this created by new as well.

BtW, an instance of p5.Vector object w/o a valid reference to p5 isn’t affected by angleMode():

Default mode RADIANS is used instead.

For example, method p5.Vector::heading() invoked by a p5.Vector instance created via new like this new p.createVector; or even new createVector; will return its result in RADIANS regardless the sketch’s current angleMode():

Well, thanks once again. What complicated mess. As a rule of thumb, I guess we generally don’t use new when creating new p5 variables?