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

181
Views
Posible usar una propiedad de objeto como argumento de un método

Básicamente, estoy tratando de crear una propiedad de objeto que creará dinámicamente una matriz basada en el constructor. Lo siguiente funciona si elimino el constructor y simplemente configuro testArray.length en algún número entero. Pero deja de funcionar cuando intento establecer la longitud con un 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 ['_', '_']

¿Tengo un problema de sintaxis o un problema de lógica? ¿Hay una mejor manera de hacer esto?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Campos de clase: asignaciones directamente dentro de un cuerpo de clase: se ejecutan antes de que se ejecute el cuerpo del constructor (suponiendo que no haya una superclase). Su código es equivalente a

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

¿Ves el problema? this.length no se ha asignado en el momento en que llama a buildArray , por lo que no está undefined .

Elimine el campo de clase y coloque esa lógica en el constructor, para que pueda utilizar el argumento del constructor. También podría deshacerse de this.length por completo en ese punto, no parece estar haciendo nada útil.

 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!