Search code examples
javascriptarraysobjectconstructor

Is there a way to call a "new" object constructor inside of an array all housed in an object?


Putting an object with both an object constructor and an array calling a "new" of the object constructor makes it so that there is an error message that states that the object constructor name is not defined.

This is my JavaScript code:

var game = {
  //constructor function for every block type
  blockType: function(name, imageX, imageY, width, height, xEffect, yEffect, passable) {
    //name is just for reference
    this.name = name;
    this.imageX = imageX;
    this.imageY = imageY;
    this.width = width;
    this.height = height;
    this.xEffect = xEffect;
    this.yEffect = yEffect;
    //if collision would be on or off
    this.passable = passable;
  },

  blockTypes: [new blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)],

};

The error message says

blockType is not defined

When I put, new game.blockType instead, there was the error message,

game is undefined

Am I declaring or calling things wrong, or is there a way to fix this?


Solution

  • new blockType references a variable with that name, but there is no such variable. Note that game.blockType is a property, not a variable.

    new game.blockType is evaluated before game is assigned a value, so that cannot work either.

    There are many solutions. For instance, first define game without the second property, and then add it:

    var game = {
      //constructor function for every block type
      blockType: function(name, imageX, imageY, width, height, xEffect, yEffect, passable) {
        //name is just for reference
        this.name = name;
        this.imageX = imageX;
        this.imageY = imageY;
        this.width = width;
        this.height = height;
        this.xEffect = xEffect;
        this.yEffect = yEffect;
        //if collision would be on or off
        this.passable = passable;
      },
    
    };
    
    game.blockTypes = [new game.blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)];
    
    console.log(game);

    Another solution is to first create blockType as a (local) variable:

    var game = (() => {
      //constructor function for every block type
      const blockType = function(name, imageX, imageY, width, height, xEffect, yEffect, passable) {
        //name is just for reference
        this.name = name;
        this.imageX = imageX;
        this.imageY = imageY;
        this.width = width;
        this.height = height;
        this.xEffect = xEffect;
        this.yEffect = yEffect;
        //if collision would be on or off
        this.passable = passable;
      };
      const blockTypes = [new blockType("basicBlack", 0, 0, 50, 50, 0, 0, false)];
      return {blockType, blockTypes};
    })(); // Immediately invoked function expression
    
    console.log(game);