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

190
Vistas
Possible to use an object property as a method's argument

Basically I am trying to create an object property that will dynamically create an array based on the constructor. The following works if I remove the constructor and simply set testArray.length to some integer. But stops working when I try setting length with a constructor.

class TestArray {
  constructor(length) {
    this.length = length;
  }

  buildArray = function(length) {
    let array = [];
    for (let i = length; i > 0; i--) {
      array.push("_");
    }
    return array;
  }

  array = this.buildArray(this.length);
}

let testArray = new TestArray(2);
console.log(testArray.array);


let testArray2 = new TestArray(2);
console.log(testArray2.array);

//[] is logged. Desired out put is ['_', '_']

Do I have syntax issue or a logic issue? Is there a plain better way to do this?

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Class fields - assignments directly inside a class body - run before the body of the constructor runs (assuming there's no superclass). Your code is equivalent to

class TestArray {
  constructor(length){
    array = this.buildArray(this.length);
    this.length = length;
  }

See the problem? this.length hasn't been assigned to at the time you call buildArray, so it's undefined.

Remove the class field, and put that logic in the constructor, so that you can make use of the constructor's argument. Might as well ditch this.length entirely at that point too, it doesn't look to be doing anything useful.

class TestArray {
  constructor(length){
    this.array = this.buildArray(length);
  }
  buildArray = function(length){
      let array = [];
      for(let i = length ; i > 0; i--){
          array.push("_");
      }
      return array;
  }
}

let testArray = new TestArray(2);
console.log(testArray.array);

about 4 years ago · Santiago Gelvez 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