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

182
Visualizações
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 Respostas
Responde à pergunta

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 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