ES5和ES6中的继承以及单例模式的实现
2018-07-15 本文已影响6人
JokerPeng
关于ES5实现继承的方式,之前的一篇文章《JavaScript 面向对象的那些事儿》已经总结过,这里为了对比和ES6的写法区别,重新再写一个例子。
一、继承
1、ES5 实现继承
var Car = function (color, name, model) {
this.color = color
this.name = name
this. model = model
this.print = function () {
console.log('My car is ' + this.color + ' ' +this.name + ' ' +this. model)
}
}
var myCar = function (color, name, model) {
Car.call(this, color, name, model)
}
myCar.prototype = Object.create(Car.prototype)
var myAudi = new myCar('red', 'Audi', 'A4L')
myAudi.print() // My car is red Audi A4L
2、ES6 实现继承
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
二、单例模式的实现
单例就是保证一个类只有一个实例,实现的方法一般是先判断实例存在与否,如果存在直接返回,如果不存在就创建了再返回,这就确保了一个类只有一个实例对象。在JavaScript里,单例作为一个命名空间提供者,从全局命名空间里提供一个唯一的访问点来访问该对象。
单例模式的核心:保证一个类仅有一个一个实例,并提供一个访问它的全局访问点。
1、ES5的单例模式写法
var Car = function (color, name, model) {
this.color = color
this.name = name
this. model = model
this.instance = null
this.print = function () {
console.log('My car is ' + this.color + ' ' +this.name + ' ' +this. model)
}
}
Car.getInstance = function(color, name, model) {
if(!this.instance) {
this.instance = new Car(color, name, model);
}
return this.instance;
}
var Audi = Car.getInstance('red','Audi', 'A4');
var Benz = Car.getInstance('white', 'Benz', 'C200');
Audi.print() // My car is red Audi A4
Benz.print() // My car is red Audi A4
说明Audi和Benz指向的是唯一实例化的对象
2、ES6的单例模式写法
class Car {
constructor (color, name, model) {
this.color = color
this.name = name
this. model = model
console.log('实例化会触发构造函数')
this.getCarInfo()
this.instance = null
}
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
单例只执行一次构造函数,如上面例子中的打印结果可以看到,在一些实际开发需求中,如连接数据库操作,点击登录按钮弹出登录框操作等等。