ES6中的类和对象

  • constructor里面的this指向创建的实例对象,普通方法里面的this指向方法的用者
  • 在ES6 中类没有变量提升,所以必须先定义类,才能通过类实例化对象
  • 类里面的共有属性和方法一定要加this使用

创建类、生成实例

  • 类里面所有的函数不需要写function
  • 多个函数方法之间不需要添加逗号分隔
     //1.创建类 class 创建一个明星类
      class Star {
        //类共有的属性放到constructor里
        constructor(uname, age) {
          this.uname = uname;
          this.age = age;
        }
        sing(song) {
          console.log(this.uname + "唱" + song);
        }
      }
      //2. 利用类创建对象 new
      var ldh = new Star("刘德华", 18);
      var zxy = new Star("张学友", 20);
      console.log(ldh);
      console.log(zxy);
      ldh.sing("冰雨");

类的继承

 //1.类的继承
      class Father {
        constructor() {}
        money() {
          console.log(100);
        }
      }
      class Son extends Father {}
      var son = new Son();
      son.money();

类继承extends和super关键字

   class Father {
        constructor(x, y) {
          this.x = x;
          this.y = y;
        }
        sum() {
          console.log(this.x + this.y);
        }
      }
      class Son extends Father {
        constructor(x, y) {
          super(x, y); //调用了父类中的构造函数
        }
      }
      var son = new Son(1, 2);
      son.sum();

注意:子类在构造函数中使用super,必须放到this前面(必须先调用父类的构造方法,再使用子类构造方法)

 class Father {
        constructor(x, y) {
          this.x = x;
          this.y = y;
        }
        sum() {
          console.log(this.x + this.y);
        }
      }
      class Son extends Father {
        constructor(x, y) {
          // 利用super 调用父类的构造函数 super必须在子类this之前调用
          super(x, y);
          this.x = x;
          this.y = y;
        }
        substract() {
          console.log(this.x - this.y);
        }
      }
      var son = new Son(5, 3);
      son.substract();
      son.sum();

静态属性和静态方法 

静态属性和静态方法只能用构造函数名或类名调用 

 class Book {
            constructor(name, author, type, info) {
                this.name = name;
                this.author = author;
                this.type = type;
                this.info = info;
            }
            //静态属性
            static address = "新华书店";
            //静态方法
            static showClassName() {
                console.log("Book");
            }
            
            // 实例方法
            sale() {
                console.log("打折");
            }
        }

        let sg = new Book("三国", "罗贯中", "小说", "一群男人的故事");
        sg.sale();
        Book.showClassName();
        console.log(Book.address)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值