通过class关键字可以定义类,可以实现单例模式,访问器属性,静态方法,extends继承
- 普通写法
function Person(name, age) {
//属性
this.name = name
this.age = age
}
//方法
Person.prototype.show = function () {
console.log(this.name, this.age)
}
let person = new Person('张三', 20)
person.show()
- es6 class写法
class Person{
//构造函数
constructor(name,age){
this.name=name
this.age=age
}
//方法
show(){
console.log(this.name,this.age)
}
}
let person = new Person('张三', 20)
person.show()
- 也可以用表达式的方式来定义
let Person = class {
constructor(name, age) {
this.name = name
this.age = age
}
}
let person = new Person('张三', 20)
console.log(person.name)
- 单例模式:用的不多
let Person = new class {
constructor(name, age) {
this.name = name
this.age = age
}
}('张三', 20)
console.log(Person.name, Person.age)
- 访问器属性(get,set)
class Person {
constructor(name, age) {
this.name = name
this.age = age
this.ageText = ''
}
//set监听属性值的变化,设置值
set age(val) {
//console.log(val)
if (val >= 18)
this.ageText = '成人'
else
this.ageText = '未成年'
}
//get获取值
get age() {
return this.ageText
}
}
let person = new Person('张三', 20)
person.age = 30 //改变值
console.log(person.ageText)
- extend是继承 super可调用父类
//父类(基类)
class Person {
constructor(name) {
this.name = name
}
run() {
console.log('人类在跑步')
}
}
//子类(派生类)
class SuperMan extends Person {
constructor(name) {//不写constructor,默认调用父类
super(name)//调用父类Person 的 constructor(name)
}
run() {
super.run()//调用继承父类方法
console.log(this.name + '在跑步')
}
}
let s1 = new SuperMan("超人")
console.log(s1.name)
s1.run()//自己没有的方法会查询调用继承父类,自己有就调用自己