skip to Main Content

why I am getting a age getter in enter image description heremain Object it should be in prototype only


class PersonCl {
  constructor(fullName, birthYear) {
    this.fullName = fullName;
    this.birthYear = birthYear;
  }

  // Instance methods
  calcAge() {
    console.log(2037 - this.birthYear);
  }

  greet() {
    console.log(`Hey ${this.fullName}`);
  }

  get age() {
    return 2037 - this.birthYear;
  }

  set fullName(name) {
    if (name.includes(' ')) this._fullName = name;
    else alert(`${name} is not a full name!`);
  }

  get fullName() {
    return this._fullName;
  }

  // Static method
  static hey() {
    console.log('Hey there 👋');
  }
}

class StudentCl extends PersonCl {
  constructor(fullName, birthYear, course) {
    // Always needs to happen first!
    super(fullName, birthYear);
    this.course = course;
  }
}

const martha = new StudentCl('Matha Jones', 2012, 'Computer Science');

console.log(martha);

maybe all the getter considered as a regular properties idk (pardon my English) is it becuase of super function or inheritance ?

2

Answers


  1. Yes, it is because of inheritance. You can make the method private to prevent it from being inherited:

    class PersonCl {
      //...
    
      get #age() {
        return 2037 - this.birthYear;
      }
    
      //...
    }
    
    Login or Signup to reply.
  2. The age getter is on the prototype, not on the main object as an own-property like the console is making you think – that’s why the age getter property in your screenshot isn’t bold like the other properties such as bithYear, course and _fullYear which are all own-properties. Since Chrome 95, it will (source):

    Always bold and sort own properties first in the Console

    Note: The getter properties in your example also appear greyed out, which indicates that they’re non-enumerable.

    Here’s another example that shows how a getter on the prototype still appears on the main object when logged, just non-bolded:

    const o = {};
    Object.defineProperty(o, "b", { // add `b` with an enumerable getter (enmerable to remove the greyed out effect to highlight the change in boldness)
      get() {
        return 2;
      },
      enumerable: true
    });
    
    const r = Object.create(o); // creates empty object `r` with `o` as the prototype
    r.a = 1; // own-property
    console.log(r);
    See browser console for output

    Example output in Chrome, notice how b is not bold, whereas a is as a is an own-property:

    enter image description here


    If you’re unsure about if something is on the main object, the most reliable check is to use Object.hasOwn(), or if you can’t support that Object.prototype.hasOwnProperty()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search