關(guān)于ES5實現(xiàn)繼承的方式倍试,之前的一篇文章《JavaScript 面向?qū)ο蟮哪切┦聝骸?/a>已經(jīng)總結(jié)過逗爹,這里為了對比和ES6的寫法區(qū)別,重新再寫一個例子蛔垢。
一击孩、繼承
1、ES5 實現(xiàn)繼承
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 實現(xiàn)繼承
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實現(xiàn)繼承
constructor (color, name, model, price) {
super(color, name, model) // 實例化子類的時候把子類的數(shù)據(jù)傳給父類
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
二巩梢、單例模式的實現(xiàn)
單例就是保證一個類只有一個實例,實現(xiàn)的方法一般是先判斷實例存在與否艺玲,如果存在直接返回括蝠,如果不存在就創(chuàng)建了再返回,這就確保了一個類只有一個實例對象饭聚。在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('實例化會觸發(fā)構(gòu)造函數(shù)')
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')
// 只打印第一次
// 實例化會觸發(fā)構(gòu)造函數(shù)
// 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
單例只執(zhí)行一次構(gòu)造函數(shù)弧满,如上面例子中的打印結(jié)果可以看到,在一些實際開發(fā)需求中此熬,如連接數(shù)據(jù)庫操作庭呜,點擊登錄按鈕彈出登錄框操作等等。