一、继承
用extends继承父类,在子类的construtor调用super()。
class Car {
constructor (color, name, model) {
this.color = color
this.name = name
this. model = model
}
print () {
console.log(`My car is ${this.color} ${this.name} ${this.model}`)
}
}
class MyCar extends Car { // 通过extends实现继承
constructor (color, name, model, price) {
super(color, name, model) // 实例化子类的时候把子类的数据传给父类
this.price = price
}
getPrice () {
console.log(`My car's price is ${this.price}`)
}
}
let myAudi = new MyCar('white', 'Audi', 'A4L', '$35000')
myAudi.getPrice() // My car's price is $35000
myAudi.print() // My car is white Audi A4L
二、单例
单例模式用于多次创建实例没有意义,甚至损坏性能的地方(如创建Db对象,连接数据库),目的是一个类只能创建出一个对象。实现的方法一般是先判断实例存在与否,如果存在直接返回,如果不存在就创建了再返回,这就确保了一个类只有一个实例对象。在JavaScript里,单例作为一个命名空间提供者,从全局命名空间里提供一个唯一的访问点来访问该对象。
单例模式的核心:保证一个类仅有一个一个实例,并提供一个访问它的全局访问点。
class Car {
constructor (color, name, model) {
this.color = color
this.name = name
this. model = model
console.log('实例化会触发构造函数')
this.getCarInfo()
}
static getInstance (color, name, model) {
if (!this.instance) {
this.instance = new Car(color, name, model)
}
return this.instance
}
print () {
console.log(`My car is ${this.color} ${this.name}`)
}
getCarInfo () {
console.log(`My car is ${this.color} ${this.name} ${this.model}`)
}
}
let myCar1 = Car.getInstance('red', 'Benz', 'C200L')
let myCar2 = Car.getInstance('white', 'Benz', 'E200L')
let myCar3 = Car.getInstance('black', 'Benz', 'C200L')
let myCar4 = Car.getInstance('graw', 'Benz', 'E200L')
// 只打印第一次
// 实例化会触发构造函数
// My car is red Benz C200L
myCar1.print()
myCar2.print()
myCar3.print()
myCar4.print()
// 会打印4次
// My car is red Benz
// My car is red Benz
// My car is red Benz
// My car is red Benz
单例只执行一次构造函数,如上面例子中的打印结果可以看到,在一些实际开发需求中,如连接数据库操作。
class Db {
//ES6类的静态方法(只能直接由类名调用的方法):static getInstance
//ES6类的静态属性:直接挂载在类名上的方法,如:Db.instance()
static getInstance() {
if (!Db.instance) {
Db.instance = new Db();
return Db.instance
}
return Db.instance;
}
constructor(name, age) {
this.name = name;
this.age = age;
//在constructor里面可以初始化地(对象一创建就开始)运行对象的方法
this.connect()
}
connect() {
console.log("I am sillyB,我连接上了数据库")
}
find() {
console.log("查询数据库")
}
}
//单例模式创建对象时,不再使用类直接创建对象,而是使用类名调用类的静态方法来创建(或返回)对象
var db1 = Db.getInstance()
var db2 = Db.getInstance()
var db3 = Db.getInstance()
db1.find()
db2.find()
db3.find()
/*结果:
I am sillyB,我连接上了数据库
查询数据库
查询数据库
查询数据库*/