Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!