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

256
Views
Si la declaración funciona en una función pero no en un método setter, y viceversa, también setter no funciona en absoluto

Estoy haciendo un proyecto en CodeCademy y necesito crear un método setter para varios estudiantes. Debería verificar si el valor es un número y, si lo es, devolver el valor; de lo contrario, registrar un error. Inicialmente se me ocurrió este código

 set numberOFStudents(val) { if(typeof val === 'number') { this._numberOfStudents = val; } else { console.log('Invalid input: numberOfStudents must be set to a Number.') } }

Pero no funcionó ya que el valor no tuvo efecto. Devolvería cadenas y números como valores. Sin embargo, cuando uso este método en una función regular, funciona perfectamente https://jsfiddle.net/Montinyek/v8zsL5et/12/ El método utilizado en el tutorial fue este:

 set numberOfStudents(val) { if(val.isNaN()) { console.log('Invalid input: numberOfStudents must be set to a Number.') } else { this._numberOfStudents = val; } }

Lo cual no funciona en una función regular ya que devuelve un error https://jsfiddle.net/Montinyek/e6k7qdcs/ Pero esto es lo que me confundió aún más, el método utilizado en el tutorial tampoco parece tener efecto. Todavía puedo establecer el número de estudiantes en una cadena y lo registrará, en lugar de registrar un error. Aquí está el jsfiddle de todo el código https://jsfiddle.net/Montinyek/1j7wL5gm/

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Es porque no estás usando el setter en tu constructor. Entonces, cuando pasa la cadena, la asigna.

Necesitas cambiar

 constructor(name, level, numberOfStudents) { this._name = name; this._level = level; this._numberOfStudents = numberOfStudents; }

A

 constructor(name, level, numberOfStudents) { this._name = name; this._level = level; this.numberOfStudents = numberOfStudents; }

entonces usa el setter y no la variable miembro. La forma en la primera lo asigna directamente a su miembro en lugar de usar el setter.

Aquí está el código completo con el cambio según su ejemplo;

 class School { constructor(name, level, numberOfStudents) { this._name = name; this._level = level; this.numberOfStudents = numberOfStudents; } get name() { return this._name; } get level() { return this._level; } get numberOfStudents() { return this._numberOfStudents; } set numberOfStudents(val) { if(typeof val !== 'number') { console.log('Invalid input: numberOfStudents must be set to a Number.') } else { this._numberOfStudents = val; } } quickFacts() { console.log(`${this.name} educates ${this.numberOfStudents} students at the ${this.level} school level.`) } static pickSubstituteTeacher(substituteTeachers) { const randInd = Math.floor(Math.random() * substituteTeachers.length) return substituteTeachers[randInd]; } } class PrimarySchool extends School { constructor(name, numberOfStudents, pickupPolicy) { super(name, 'primary', numberOfStudents) this._pickupPolicy = pickupPolicy; } get pickupPolicy() { return this._pickupPolicy; } } class HighSchool extends School { constructor(name, numberOfStudents, sportsTeams) { super(name, 'high', numberOfStudents) this._sportsTeams = sportsTeams; } get sportsTeams() { return this._sportsTeams; } } const lorraineHansburry = new PrimarySchool('Lorraine Hansbury', 'g', 'Students must be picked up by a parent, guardian, or a family member over the age of 13.'); lorraineHansburry.quickFacts(); const alSmith = new HighSchool('Al E. Smith', 415, ['Baseball', 'Basketball', 'Volleyball', 'Track and Field']) alSmith.quickFacts();

aquí está el jsfiddle guardado que muestra su funcionamiento

https://jsfiddle.net/6qoadu27/6/

about 4 years ago · Juan Pablo Isaza 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!