委托模式
原型模式與委托模式實(shí)現(xiàn)”繼承“的對比
function Phone(name, type) {
this.name = name
this.type = type
}
Phone.prototype.getName = function () {
console.log(this.name)
}
function Xiaomi(name, type) {
Phone.call(this, name, type)
}
Xiaomi.prototype = Object.create(Phone.prototype)
const k30 = new Xiaomi('Readmi', 'k30')
k30.getName()
// 定義“父級”對象
const Phone = {
setName: function (name) {
this.name = name
},
setType: function (type) {
this.type = type
},
getName: function () {
console.log(this.name)
}
}
// 定義“子級”對象赤拒,并關(guān)聯(lián)“父級”對象
const Xiaomi = Object.create(Phone)
Xiaomi.getInit = function (name, type) {
this.setName(name)
this.setType(type)
}
Xiaomi.getInfo = function () {
console.log(this.name, this.type)
}
// 初始化+使用
const Readmi = Object.create(Xiaomi)
Readmi.getInit('Readmi', 'k30')
Readmi.getInfo()
class Phone {
constructor(name, type) {
this.name = name
this.type = type
}
getName() {
console.log(this.name)
}
}
class Xiaomi extends Phone {
constructor(name, type) {
super(name, type)
}
}
const k30 = new Xiaomi('Readmi', 'k30')
k30.getName()
- 你可能會認(rèn)為ES6的class語法是向JavaScript中引入了一種新的“ 類”機(jī)制烈涮, 其實(shí)不是這樣客燕。class基本上只是現(xiàn)有[[Prototype]](委托Q恰)機(jī)制的一種語法糖暴匠。*