创建对象的几种方式
const obj1_1 = { name: 'obj1' }
const obj1_2 = new Object({ name: 'obj1' })
const Fn = function() {
this.name = 'obj2'
}
const obj2 = new Fn()
const P = {name: 'obj3'}
const obj3 = Object.create(P)
实现继承的几种方式
1、借助构造函数实现继承
function Parent1() {
this.name = 'parent1'
}
function Child1() {
Parent1.call(this)
this.type = 'child'
}
const s1 = new Child1()
Parent1.prototype.say = function() {}
console.log(s1.say);
2、借助原型链实现继承
function Parent2() {
this.name = 'parent2'
this.arr = [1, 2, 3]
}
function Child2() {
this.type = 'child'
}
Child2.prototype = new Parent2()
const s1 = new Child2()
const s2 = new Child2()
s1.arr.push(4)
console.log(s2.arr);
3、组合继承
function Parent3() {
this.name = 'parent3'
this.arr = [1,2,3]
}
function Child3() {
Parent3.call(this)
this.type = 'child3'
}
Child3.prototype = new Parent3()
4、组合继承的优化1
function Parent4() {
this.name = 'parent4'
this.arr = [1,2,3]
}
function Child4() {
Parent4.call(this)
this.type = 'child4'
}
Child4.prototype = Parent4.prototype
5、组合继承的优化2
function Parent5() {
this.name = 'parent5'
this.arr = [1,2,3]
}
function Child5() {
Parent5.call(this)
this.type = 'child5'
}
Child5.prototype = Object.create(Parent5.prototype)
Child5.prototype.constructor = Child5