1

I want to make a handler for cases where the function is passed nothing, e.g. var v = Vector() as opposed to Vector(2,5,1) for example.

var Vector3 = function(x, y, z) {
this.x = x; this.y = y; this.z = z;

if (Vector3() === null)
{
   this.x = 0;
   this.y = 0;
   this.z = 0;
}
FluffyKitten
  • 13,824
  • 10
  • 39
  • 52
NinStarRune
  • 23
  • 1
  • 7

1 Answers1

1

You can use default parameters which default to 0 when they're not passed:

function Vector(x=0, y=0, z=0) {
  this.x = x;
  this.y = y;
  this.z = z;
}
console.log(new Vector(2,5,1));
console.log(new Vector());
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Unfortunately, I'm not allowed to touch the original snippet of code. I have to do it outside of the function declaration. – NinStarRune Sep 06 '20 at 04:15
  • 1
    Your original snippet's logic is quite broken. `if (Vector3() === null)` does not make any sense - the function doesn't appear to return anything when not called with `new` (it will return `undefined`), and if called with `new`, it will always return an object. No matter what, you really should fix the original snippet. – CertainPerformance Sep 06 '20 at 04:18
  • ```var Vector3 = function(x, y, z) { this.x = x; this.y = y; this.z = z;``` is the original snippet. the broken code below is my attempt at trying to get javascript to do something. – NinStarRune Sep 06 '20 at 18:09