Home > Enterprise >  Possible to use an object property as a method's argument
Possible to use an object property as a method's argument

Time:07-19

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?

CodePudding user response:

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

  • Related