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>