创建对象

image.png

案例

image.png
输出
image.png

继承

image.png
image.png
静态只能通过类名调用
image.png

注意点

  • 在 ES6 中类没有变量提升,所以必须先定义类,才能通过类实例化对象
  • 类里面的共有属性和方法一定要加 this 使用
  • 类里面的 this 指向问题:constructor 里面的 this 指向实例对象, 方法里面的 this 指向这个方法的调用者
    1. let that;
    2. class Star {
    3. constructor (uname, age) {
    4. that = this;
    5. this.uname = uname;
    6. this.age = age;
    7. // btn按钮调用sing方法
    8. this.btn = document.querySelector("button");
    9. this.btn.onclick = this.sing;
    10. // constructor 里面的this 指向的是 创建的实例对象
    11. console.log("constructor: ", this);
    12. }
    13. sing() {
    14. // 这个sing方法里面的 this 指向的是 btn 这个按钮,因为这个按钮调用了这个函数
    15. console.log("sing:", this); // button
    16. console.log(that.uname); // that里面存储的是constructor里面的this
    17. }
    18. dance() {
    19. // 这个dance里面的this 指向的是实例对象 ldh 因为ldh 调用了这个函数
    20. console.log("dance:", this);
    21. }
    22. }
    23. let rick = new Star("Rick", 20);
    24. rick.dance();