0%

729_类和对象

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>点击我</button>
    <script>
      class Star {
        constructor(name, age) {
          //这里的this指的是类的实例化对象
          this.name = name;
          this.age = age;
        }
        //添加公共方法,这里的方法被放在原型对象身上
        sing(song) {
          console.log(this.name + song);
        }
      }

      let ldh = new Star("刘德华", 18);
      console.log(ldh.age);
      ldh.sing("ldh唱的");

      console.log("-------------------------------------");
      class Father {
        constructor(x, y) {
          //公共的属性和方法一定要加this
          this.x = x;
          this.y = y;
          this.btn = document.querySelector("button");
          this.btn.onclick = this.say;
        }
        sum() {
          console.log(this.x + this.y);
        }
        say() {
          console.log("我是爸爸");
        }
      }

      //extends会继承父类中的属性和方法
      class Son extends Father {
        constructor(x, y) {
          //由于子类和父类的this指向不同,这里用了super关键字调用了父类的构造函数
          super(x, y);
          //super关键字一定要写在this之前
          this.x = x;
          this.y = y;
          this.btn = document.querySelector("button");
          this.btn.onclick = this.saySon;
        }
        say() {
          //在子类中可以通过/super关键字调用父类中的普通函数
          super.say();
        }

        saySon() {
          console.log("我是龟儿");
          //this表示谁调用就指向谁
          //这里面的this指向的是button,因为button调用了他
          console.log(this); //如果使用点击调用this就是<button>点击我</button>
          //如果不点击直接通过son.saySon();调用this就是Son
        }

        jianfa() {
          //这里面的this指向的是son,因为son调用了他
          console.log(this); //Son {x: 2, y: 1, btn: button}
          console.log(this.x - this.y);
        }
      }

      var son = new Son(2, 1);
      son.sum();
      //查找原则:先去子类找,找不到再去父类里面找
      son.say();
      son.jianfa();
      son.saySon();
    </script>
  </body>
</html>