JS常见继承方式

文章探讨了JavaScript中不同类型的继承机制,包括ES6的类继承和ES5的原型链、构造函数、组合以及组合寄生继承。各种继承方式有其优缺点,例如原型链继承不支持给父类传参,构造函数继承无法继承原型链上的属性,而组合继承和组合寄生继承则在解决这些问题上提供了方案,但也存在如重复调用父类构造函数的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


// 1. ES6
// class Parent {
//     constructor(name) {
//         this.name = name
//     }
//     say () {
//         console.log(this.name);
//     }
// }
// class Child extends Parent { }
// let son = new Child('小明')
// son.say() // 小明

// 2. ES5 - 原型链继承 - 构造函数继承 - 组合继承 - 组合寄生继承
// 1. 原型链继承
// 缺点 1. 如果某个继承属性是引用类型的数据 一旦某个实例修改了 那么这个属性都会被修改
//      2. 不能给父类传参 也就是没有实现super方法
//      3. 不能实现多继承
// function Parent (name) {
//     this.name = name
// }
// Parent.prototype.sayHello = function () {
//     console.log('你好');
// }
// function Child (id) {
//     this.id = id
// }
// Child.prototype = new Parent()
// Child.constructor = Child

// 2. 构造函数继承
// 缺点 1. 无法继承父类原型链上的属性和方法
// function Parent (name, age) {
//     this.name = name
//     this.age = age
// }
// function Child (id) {
//     Parent.apply(this, Array.prototype.slice.call(arguments, 1))
//     this.id = id
// }

// 3. 组合继承
// 缺点 1. 父类构造函数调用了两次 子类继承的属性会继承两次 一次是子类型实例继承 一次是子类原型链继承 实例继承的属性覆盖了原型继承的属性
// function Parent (name, age) {
//     this.name = name
//     this.age = age
// }
// Parent.prototype.sayHello = function () {
//     console.log('你好');
// }
// function Child (id) {
//     Parent.apply(this, Array.prototype.slice.call(arguments, 1))
//     this.id = id
// }
// Child.prototype = new Parent()
// Child.constructor = Child

// 4. 组合寄生继承
function Parent (name, age) {
    this.name = name
    this.age = age
}
Parent.prototype.sayHello = function () {
    console.log('你好');
}
function Child (id) {
    Parent.apply(this, Array.prototype.slice.call(arguments, 1))
    this.id = id
}
// Child.prototype = Object.create(Parent.prototype)
Child.prototype = inherit(Parent.prototype)
Child.constructor = Child

function inherit (p) { // 利用new() 模拟 Object.create()
    function fn () { }
    fn.prototype = p
    return new fn()
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值