javascript - Confusion about class and super in ES6
黄舟
黄舟 2017-05-19 10:31:04
0
2
755
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?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
世界只因有你

Yes, the child’s book does not pass parameters

        class book extends Book{
            constructor(book1, book2) {
                super(book1, book2);
            }
            toSay() {
                super.getName();
            }
        }
左手右手慢动作

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template