// 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()
}
JS常见继承方式
最新推荐文章于 2025-08-05 17:55:38 发布