Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
How do i initialise an array of object in constructor in JavaScript

I would like to create a class with an array of object in the constructor. The idea is to create rects in a canvas with the values inside the objects.

I have this array:

const blueBoxs = [
  { x: 38, y: 31, w: 50, h: 50 },
  { x: 47, y: 31, w: 25, h: 19 },
]

I tried the following:

class Collision {   
  constructor (boxs) {
    this.boxs=boxs;
  };

  createBox(boxs=[]){
    for (let box of boxs) {
      ctx.fillStyle = 'blue'
      ctx.fillRect(box.x, box.y, box.w, box.h)
    }
    return
  };
};

let createBluebox= new Collision(blueBoxs);
createBluebox.createBox();

Thanks for your help.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

As already written, the addition of this works. See example with this.boxs

const blueBoxs = [
    {
        x: 38,
        y: 31,
        w:50,
        h:50,
       },
    { 
        x: 47,
        y: 31,
        w:25,
        h:19,
     } ]

class Collision {   
  constructor (boxs) {
      this.boxs=boxs;
  };

  createBox(boxs=[]){
      for (let box of this.boxs) {
        ctx.fillStyle = 'blue'
        ctx.fillRect(box.x, box.y, box.w, box.h)
      }
      return
  };
 
};

let canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

let createBluebox= new Collision(blueBoxs); 
createBluebox.createBox();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

about 4 years ago · Juan Pablo Isaza Relatório

0

I forgot the this keyword everywhere. Thanks for all!

    class Collision {   
  constructor (boxs, ctx) {
      this.boxs=boxs;
      this.ctx=ctx;
  };

  createBox(){
      for (let box of this.boxs) {
        this.ctx.fillStyle = 'blue'
        this.ctx.fillRect(box.x, box.y, box.w, box.h)
      }
      return
  };
 
};
let createBluebox= new Collision(blueBoxs, ctx); 
createBluebox.createBox();
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda