Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
Unable to pass the object as parameter in constructor
class Projectile{
    constructor(position, velocity){
        this.position= position
        this.velocity = velocity
        this.radius = 30
    }

    draw(){
        c.beginPath()
        console.log(this.position.x + "  " + this.position.y)
        c.arc(500, 500, this.radius, 0, Math.PI * 2)
        c.fillStyle = "red"
        c.fill()
        c.closePath()
    }

    update(){
        this.draw()
        this.position.x += this.velocity.x
        this.position.y += this.velocity.y
    }
}

This is my class. I have made a constructor that takes two objects. I have used following line of code to make a new object of class. It should be an array of objects.

 const projectiles = [new Projectile({
    position: {
        x:300,
        y:300
    },
    velocity: {
        x:0,
        y:0
    }
})]

The problem is when I am printing the value of this.position.x and this.position.y in console , it is printing undefined. I want the value that I have passed while creating the object.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

update(){
    console.log(this); // position: {position: {...}, velocity: {...}}, velocity: undefined, ...
    this.draw()
    this.position.x += this.velocity.x
    this.position.y += this.velocity.y
}

You are passing an argument only to the parameter position.

so you should change change like this

 const projectiles = [new Projectile(
    // position
    {
        x:300,
        y:300
    },
    // velocity
    {
        x:0,
        y:0
    }
)]
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda