Class(类)
作为对象的模板,通过class关键字,可以定义类。
- class声明类
- constructor 定义构造函数初始化
- extends 继承父类
- super 调用父级构造方法
- static 定义静态方法和属性
- 父类方法可以重写
class Phone {
constructor(brand, price) {
this.brand = brand
this.price = price
}
//方法必须使用该语法,不能使用ES5的对象完整形式
call() {
console.log('打电话请给我')
}
}
let Huawei = new Phone('华为', '6666')
console.log(Huawei)
静态成员
static,属于类,不属于实例对象
class Phone {
static name = '手机'
static change() {
console.log('111111111')
}
}
let sanxing = new Phone()
console.log(sanxing.name) //undefined
console.log(Phone.name) //手机
类继承
class Phone {
//构造方法
constructor(brand, price) {
this.brand = brand
this.price = price
}
//父类的成员属性
call() {
console.log('赶紧打电话!!!')
}
}
// 继承父类的方法
class SmallPhone extends Phone {
constructor(brand, price, color, size) {
super(brand, price) //等同于Phone.call(this,brand,price)
this.color = color
this.size = size
}
phone() {
console.log('拍照')
}
playgame() {
console.log('玩游戏')
}
}
const xiaomi = new SmallPhone('小米', 6666, '白色', '4.4yincun')
console.log(xiaomi)
xiaomi.call()
xiaomi.phone()
xiaomi.playgame()
子类对父类方法的重写
getter和1setter设置
class Phone {
get price() {
//动态变化的数据
console.log('价格属性被读取了')
return '666'
}
set price(newValue) {
//设置的值
console.log('价格属性被修改了')
}
}
let s = new Phone()
console.log(s.price)
s.price = 'free'
每日一句
学会简单生活,简单是一种平凡,但不平庸。