一、原型链继承
function Parent(name) {
this.name = name
this.frineds = []
}
Parent.prototype.eating = function () {
console.log(this.name + 'eating')
}
function Child(age) {
this.age = age
}
Child.prototype.running = function () {
console.log('running')
}
Child.prototype = new Parent()
let obj = new Child(12)
obj.frineds.push(123)
let obj2 = new Child(11)
console.log(obj.eating())
console.log(obj.frineds, obj2.frineds)
复制代码
缺点:
- 无法给继承属性赋值
- 修改父元素的引用属性可能会影响其他对象的该引用属性
- 子对象无法查看继承属性
二、构造继承
function Parent(name) {
this.name = name
this.frineds = []
}
Parent.prototype.eating = function () {
console.log(this.name + 'eating')
}
function Child(age, name) {
Parent.call(this, name)
this.age = age
}
Child.prototype = new Parent()
Child.prototype.running = function () {
console.log('running')
}
let obj = new Child(12, 'a')
obj.frineds.push(123)
let obj2 = new Child(11, 'b')
console.log(obj.eating())
console.log(obj.frineds, obj2.frineds)
复制代码
优点:解决了原型链继承的三个缺点 缺点:
- 父构造函数调用了两次
- 会多生成一份继承属性实例
三、寄生式继承
let parentObj = {
running: function () {
console.log('running')
}
}
function createChild(name) {
let child = Object.create(parentObj)
child.name = name
return child
}
let child1 = createChild('aa')
child1.running()
复制代码
四、寄生组合继承
function Parent(name) {
this.name = name
}
Parent.prototype.eating = function () {
console.log(this.name + ' eating')
}
function Child(age, name) {
Parent.call(this, name)
this.age = age
}
inheritPrototype(Child, Parent)
function inheritPrototype(SubType, SuperType) {
SubType.prototype = Object.create(SuperType.prototype)
Object.defineProperty(SubType.prototype, "constructor", {
enumerable: false,
configurable: true,
writable: true,
value: SubType
})
}
Child.prototype.running = function () {
console.log('running')
}
let obj = new Child(12, 'aaaa')
console.log(obj.eating())
复制代码