ES6-类class

ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。

静态方法:不会被实例继承,而是直接通过类来调用

<script>
      class peopler {
        constructor(name, age) {
          this.name = name;
          this.age = age;
        }
        show() {
          console.log(`球员信息:姓名:${this.name},年龄:${this.age}`);
        }
        static info() {
          console.log("这是一个定义球员的类");
        }
      }
      peopler.info(); //静态方法只能有类调用,不能变量调用
      let people = new peopler("lmx", "21");
      people.show();
</script>

constructor 方法

constructor()方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor()方法,如果没有显式定义,一个空的constructor()方法会被默认添加。

class Point {
}

// 等同于
class Point {
  constructor() {}
}

上面代码中,定义了一个空的类Point,JavaScript 引擎会自动为它添加一个空的constructor()方法。

setter/getter方法

class peopler {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
      set sex(val) {
        this._sex = val;
      }
      get sex() {
        return this._sex;
      }
}
let people = new peopler("lmx", 21);

console.log(people); // {name: "lmx", age: 21}
people.sex = "男";
console.log(people.sex); //男
console.log(people); //{name: "lmx", age: 21, _sex: "男"}

类继承

 <script>
      class Car {
        constructor(brand) {
          this.brand = brand;
        }
        show() {
          console.log(`汽车品牌为:${this.brand}`);
        }
      }
      class Lexus extends Car {
        constructor(brand, model) {
          super(brand);
          this.model = model;
        }
        getPrice() {
          switch (this.model) {
            case "RX":
              return 60;
            case "UX":
              return 40;
            default:
              throw new Error("未知车型");
          }
        }
      }
  let mycar = new Lexus("Lexus", "RX");
  mycar.show();// 汽车品牌为:Lexus
  console.log("价格为:", mycar.getPrice(), "万");
  //价格为: 60 万
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值