Search code examples
javascriptfunctionreturn

How to return a function inside of a function? (like p5.js createVector)


function createVector(_x, _y, _z) {
 if (_x == undefined) {
  _x = 0;
 }

 if (_y == undefined) {
  _y = 0;
 }

 if (_z == undefined) {
  _z = 0;
 }

 function add(_addX, _addY, _addZ) {
  numX += _addX;
  numY += _addY;
  numZ += _addZ;
 }

 let numX = _x;
 let numY = _y;
 let numZ = _z;

 return {
  x: numX,
  y: numY,
  z: numZ,
  add()
 };
}

so far im getting an error that says Unexpected token '}' im really trying to just get a recreation of the p5.js createvector() method as I am creating my own library for personal use. Any help would be much appreciated - Jack


Solution

  • Since you are trying to emulate a constructor pattern, make the following adjustments to follow the pattern.

    The purpose of adding the add function to the prototype is that if you add it to the createVector object like you have now, every new instance of createVector will have its own instance of that function as well. Adding it to the prototype ensures that only one copy of the function exists.

    function createVector(_x, _y, _z) {
      if (_x == undefined) {
        _x = 0;
      }
    
      if (_y == undefined) {
        _y = 0;
      }
    
      if (_z == undefined) {
        _z = 0;
      }
      this.x = _x;
      this.y = _y;
      this.z = _z;
    }
    
    createVector.prototype.add = function(x, y, z) {
        this.x += x;
        this.y += y;
        this.z += z;
    }
    
    var vec = new createVector(1, 2, 3);
    console.log(vec);
    vec.add(2, 3, 4);
    console.log(vec);

    You could even create an add function that takes another vector as an argument:

    function createVector(_x, _y, _z) {
      if (_x == undefined) {_x = 0;}
      if (_y == undefined) {_y = 0;}
      if (_z == undefined) {_z = 0;}
      this.x = _x;
      this.y = _y;
      this.z = _z;
    }
    
    createVector.prototype.add = function(vec) {
      this.x += vec.x;
      this.y += vec.y;
      this.z += vec.z;
    }
    
    var vec1 = new createVector(1, 2, 3);
    var vec2 = new createVector(2, 3, 4);
    
    console.log(vec1);
    
    vec1.add(vec2);
    console.log(vec1)