委托模式
原型模式与委托模式实现”继承“的对比
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)
}
}
// 定义“子级”对象,并关联“父级”对象
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()
- 你可能会认为ES6的class语法是向JavaScript中引入了一种新的“ 类”机制, 其实不是这样。class基本上只是现有[[Prototype]](委托!)机制的一种语法糖。*