9. Inheritance IV


#1

https://www.codecademy.com/courses/learn-javascript-classes/lessons/classes/exercises/inheritance-iv?action=lesson_resume&course_redirect=introduction-to-javascript

I’m not stuck, I just don’t understand why “_behavior” got inherited. I thought that, besides using “extends”, one had to also use “super()” to specifically indicate what property/method gets inherited. I mean, if everything gets inherited by default, then why have “super()” at all? I mean, the child’s class “_behavior” already points to the super class “_behavior” without the need of “super()”, then why does the “name” property needs it?

Also, how about when you DON’T want something to get inherited?

Excerpt from exercise:

class Animal {
  constructor(name) {
    this._name = name;
    this._behavior = 0;
  }

  get name() {
    return this._name;
  }

  get behavior() {
    return this._behavior;
  }

  incrementBehavior() {
    this._behavior++;
  }
} 


class Cat extends Animal {
  constructor(name, usesLitter) {
    super(name);
    this._usesLitter = usesLitter;
  }
}

const bryceCat = new Cat('Bryce', false);

// Now consider a more involved example and try to answer the following question: What will the code below log to the console?

bryceCat.incrementBehavior(); // Call .incrementBehavior() on Cat instance 
console.log(bryceCat.behavior); // Log value saved to behavior

// The correct answer is 1. But why?

// The Cat class inherits the _behavior property, behavior getter, and the .incrementBehavior() method from the Animal class.
// When we created the bryceCat instance, the Animal constructor set the _behavior property to zero.
// The first line of code calls the inherited .incrementBehavior() method, which increases the bryceCat _behavior value from zero to one.
// The second line of code calls the behavior getter and logs the value saved to _behavior (1).


#2

super() is used to call and access the parent object

If you were to remove the super() within the class Cat it would throw a ReferenceError. The class Cat is being derived from Animal and wouldnt be able to recognize this without super()