Home  >  Q&A  >  body text

javascript - Confusion about class and super in ES6

class Book{
            constructor(book1,book2) {
                this.book1 = book1;
                this.book2 = book2;
            }
            getName() {
                alert(this.book1+this.book2)
            }
        }
        class book extends Book{
            constructor() {
                super(book1,book2);
            }
            toSay() {
                super.getName();
            }
        }
        var cp = new book("javascript guide","javascript best pattern");

After reading Ruan Yifeng’s ES6 tutorial, I am still a little confused about class and super. First create a Book class
Then create a subclass book to inherit the parent class Book, super calls the constructor of the parent class, and calls it in toSay The getName() method of the parent class, the browser reports an error

The following is an example of Ruan Yifeng's class. The code structure only defines a color attribute on the subclass more than me. If my subclass does not need its own attributes, can I completely call the attributes and methods of the parent class?

class Point {
          constructor(x, y) {
            this.x = x;
            this.y = y;
          }

          toString() {
            return '(' + this.x + ', ' + this.y + ')';
          }
     }
         class ColorPoint extends Point {
              constructor(x, y, color) {
                super(x, y); // 调用父类的constructor(x, y)
                this.color = color;
              }

              toString() {
                return this.color + ' ' + super.toString(); // 调用父类的toString()
              }
        }

There is another doubt
Teacher Ruan said that super() must be defined in subclasses


But my code does not have super, the browser executed it


Is that why?

黄舟黄舟2733 days ago736

reply all(2)I'll reply

  • 世界只因有你

    世界只因有你2017-05-19 10:33:04

    Yes, the child’s book does not pass parameters

            class book extends Book{
                constructor(book1, book2) {
                    super(book1, book2);
                }
                toSay() {
                    super.getName();
                }
            }

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:33:04

    Correct answer upstairs.
    As teacher Ruan Yifeng said:

    • In the first case, when super is called as a function, it represents the constructor of the parent class.

    • In the second case, when super is used as an object, in ordinary methods, it points to the prototype object of the parent class; in static methods, it points to the parent class.

    reply
    0
  • Cancelreply