0

I define a class as follows:

class Person {
  constructor() {
    this.age = 60;
  }
  showAge() {
    return console.log(this.age);
  }
}

const mark = new Person();
mark.showAge();  //60

How do I change this.age that the object mark will initialize with from 60 to another number without simply assigning a new value in the constructor?

The idea is to then create new objects from the class which all instantiate with this new value and not 60 for this.age.

Behemoth
  • 5,389
  • 4
  • 16
  • 40
btew2102
  • 73
  • 6
  • 1
    you can pass the age into the constructor `new Person(60);` and then assign it in your constructor: `constructor(age) { this.age = age;}` – Nick Parsons Aug 23 '21 at 11:48
  • 2
    watch this [JavaScript Class Getter/Setter](https://stackoverflow.com/a/49895210/5385135) – Bahador Raghibizadeh Aug 23 '21 at 11:48
  • 2
    Pass the values to the constructor: `constructor(age) { this.age = age; }` and then create a new object as: `new Person(23)` or `new Person(60)`, etc. – Yousaf Aug 23 '21 at 11:48

0 Answers0