1、如果使用es6定义一个类
// 使用class关键字申明一个类
class Person{
constructor(name,age){ // 类的构造函数,实例化的时候执行
this._name=name
this._age=age
}
setName(name){
this._name=name
}
getName(){
console.log(this._name)
}
}
var p=new Person('张三',18) // 实例化对象
p.getName()
p.setName('李四')
p.getName()
// 输出: 张三
// 李四
2、es6中如何继承类
class Person{
constructor(name,age){
this.name=name
this.age=age
}
getInfo(){
console.log(`姓名:${this.name} 年龄:${this.age}`)
}
run(){
console.log('run')
}
}
class Web extends Person{ // 继承Person (使用extends关键字)
constructor(name,age,sex){
super(name,age) // 实例化子类的时候把子类的数据传给父类
this.sex=sex
}
print(){
console.log(`${this.name}----${this.age}----${this.sex}`)
}
}
var w=new Web('张三','30','男')
w.getInfo()
w.print()
// 打印结果
// 姓名:张三 年龄:30
// 张三----30----男
3、es6中如何声明类的静态方法
// es6中的静态方法
class Person{
constructor(name){
this._name=name
}
run(){ // 实例方法
console.log(this._name)
}
static work(){ // 静态方法
console.log('这是es6中的静态方法')
}
}
var p=new Person('张三')
p.run()
Person.work()
Person.instance='这是静态方法的属性'
console.log(Person.instance)
// 输出结果
// 张三
// 这是es6中的静态方法
// 这是静态方法的属性
4、es6中实现对象的单例
class Db{
static getInstance(){ // 静态方法实现单例
if(!Db.instance){
Db.instance=new Db()
}
return Db.instance
}
constructor(){
console.log('实例化时触发构造函数')
}
}
// var myDb1=new Db()
// var myDb2=new Db()
// var myDb3=new Db()
// 单例
var myDb1=Db.getInstance()
var myDb2=Db.getInstance()
var myDb3=Db.getInstance()
// 只实例化一次
// myDb1 myDb2 myDb3都是同一个实例,都可以调用实例方法