面向对象与继承

创建对象的几种方式

// 创建对象的三种方式
// 第一种
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值