0

I always thought that calling super() was practically like copy pasting the properties of the parent into the child class.

**Here super() is called to avoid duplicating the constructor parts' that are common between Rectangle and Square. ** MDN

I read on MDN that you need to extend a class and call super() to be able to. And also

The super keyword is used to access and call functions on an object's parent.

MDN

which I do not fully understand.

I tested those in this example:

class Logger extends Array {
    log() {
        let i = 0
        for (const el of this) {
            console.log(this[i], el)
            i++
        }
        return;
    }
}
a = new Logger(1, 2, 3)
a.log()
a.push(6)

But neither super() is needed for accessing this[i] or calling a.push() any hints folks?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Mah Neh
  • 84
  • 6
  • Only if you override something you need super – Daniel A. White May 30 '22 at 19:49
  • 1
    You neither have a constructor, not access anything specific on the parent. Why would the code need `super`? – VLAZ May 30 '22 at 19:49
  • what do you mean @VLAZ that is a constructor, SAME as the provided link in MDN – Mah Neh May 30 '22 at 19:50
  • @DanielA.White thank you that clicked. Does not answer the second part though. – Mah Neh May 30 '22 at 19:53
  • There is no constructor here. A constructor is declared by calling it `constructor`. There is no such thing in the code. Ergo, you have no constructor here. You have *a class definition*. At best, there is an implicit constructor which again does not necessitate the keyword `super`. – VLAZ May 30 '22 at 19:53
  • So the parent class props are available for the methods but not inside the constructor unless I call super(), it is like inside the constructor they are unexistent otherwise ? @VLAZ – Mah Neh May 30 '22 at 20:00
  • If you define a constructor in a child class, you need to call `super()`. The code would not work otherwise. It's how the language defines classes. That's really about it. Other than that, you need to use `super` if you explicitly want to access something from the parent. Neither of which is the case here. – VLAZ May 30 '22 at 20:04
  • "*calling `super()` was practically like copy pasting the properties of the parent into the child class.*" - [not quite](https://stackoverflow.com/a/42583101/1048572), no. "*you need to extend a class and call `super()` to be able to*" - [not always](https://stackoverflow.com/a/41351048/1048572). "*access and call functions on an object's parent.*" - that refers to `super[i]` and `super.push(…)` syntax, as opposed to the `super(…)` syntax found in a constructor. And while they aren't needed *here*, they would in fact work. They are needed when overridding a method or property. – Bergi May 30 '22 at 20:05
  • Thank you I am only getting into it and was quite confused. This makes some better model in my head @Bergi – Mah Neh May 31 '22 at 11:39

0 Answers0