1. 定义类
构造函数(Constructor)在对象创建或者实例化时候被调用的方法。通常使用该方法来初始化数据成员和所需资源。构造器Constructor在js不能被继承,因此不能重写Overriding,但可以被重载Overloading
class Person {
constructor(name) {
this.name = name;
this.sex = '男'
this.money = true
}
getName() {
// this 指向Person类
console.log(this)
console.log(`姓名:${this.name}`)
}
setName(name) {
this.name = name
}
}
let p1 = new Person("doudou");
// p1.setName('流浪')
p1.getName()
2. 继承
class Father {
constructor(name) {
this.name = name;
this.sex = '男'
this.money = true
}
getName() {
console.log(this)
console.log(`姓名:${this.name}`)
}
setName(name) {
this.name = name
}
}
class Son extends Father {
constructor(name) {
super(name)
}
getInfo() {
console.log(this)
}
static people() {
console.log('这个是es6中的静态方法;')
}
}
let s4 = new Son('doudou')
s4.getInfo()
Son.people()