创建对象的几种方式
// 创建对象的三种方式
// 第一种
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的this指向Child1的实例对象,让实例对象有Parent1的属性
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'
}
// 原理:将父类的实例对象赋值给子类的原型对象,
// 子类的__proto__属性指向父类的实例对象,里面有父类的属性方法和原型链
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()
// 缺点1:Parent3会执行两次
// 缺点2:Child3.prototype.constractor不是Child3,而是Parent3
4、组合继承的优化1
优化掉:Parent4会执行两次
function Parent4() {
this.name = 'parent4'
this.arr = [1,2,3]
}
function Child4() {
Parent4.call(this)
this.type = 'child4'
}
Child4.prototype = Parent4.prototype
5、组合继承的优化2
优化掉:Child5.prototype.constractor不是Child5,而是Parent5
function Parent5() {
this.name = 'parent5'
this.arr = [1,2,3]
}
function Child5() {
Parent5.call(this)
this.type = 'child5'
}
// Child5.prototype.__proto__ = Parent5.prototype
Child5.prototype = Object.create(Parent5.prototype)
Child5.prototype.constructor = Child5