继承的本质: 子类继承父类的属性和方法。(目的是让子类的实例能够调取父类的属性和方法。)markdown
原理: 让父类中的属性和方法在子类实例的原型链上函数
CHILD.prototype = new PARENT()ui
CHILD.prototype.constrctor = CHILDthis
特色:spa
// 原型链继承举🌰
// 父类
function Parent(x) {
this.x = x
}
Parent.prototye.getX = function() {
console.log(this.x)
}
// 子类
function Child(y) {
this.y = y
}
// 继承
Child.prototype = new Parent('y') // 子类的原型指向父类的实例
Child.prototype.constrctor = Child // 保证子类构造函数的完整性
Child.prototype.getY = function() {
console.log(this.y)
}
const child = new Child('x')
child.y // y 成功访问子类属性
child.x // x 成功访问父类属性
child.getX() // x 成功调用父类方法
child.getY() // y 成功调用子类自己方法
// 子类能够经过 CHILD.prototype.__proto__修改父类,并对父类的其余实例形成影响
Child.prototype.__proto__.other = function () {
console.log('other')
}
const parent = new Parent(200)
parent.other() // other
复制代码
// CALL继承举🌰
// 父类
function Parent(x) {
this.x = x
this.thisGetX = function () {
console.log(this.x)
}
}
Parent.prototype.getX = function () {
console.log(this.x)
}
// 子类
function Child(y) {
// this => Child的实例
Parent.call(this, 200)
this.y = y
}
Child.prototype.getY = function () {
console.log(this.y)
}
const child = new Child(100)
console.log(child.x) // 成功访问父类属性
child.getX() // 报错 没法访问父类原型链上的属性和方法
复制代码
// 寄生组合继承举🌰
// 父类
function Parent(x) {
this.x = x
this.thisGetX = function () {
console.log(this.x)
}
}
Parent.prototype.getX = function () {
console.log(this.x)
}
// 子类
function Child(y) {
// this => Child的实例
Parent.call(this, 200)
this.y = y
}
// Object.create => 建立一个空对象,让空对象__proto__指向 Parent.prototype
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
const child = new Child(100)
console.log(child.x) // 成功访问父类属性
child.getX() // 报错 没法访问父类原型链上的属性和方法
// 实现object.create方法
function create(obj) {
function Fn() Fn.prototype = obj return new Fn() } 复制代码
// 父类
// ES6中基于class创造出来的类不能看成普通函数执行、不容许重定向原型的指向
class Parent {
constructor(x) {
this.x = x
}
getX() {
console.log(this.x)
}
}
// 子类
// class Child {
// constructor(y) {
// this.y = y
// }
// getY() {
// console.log(this.y)
// }
// }
// ES6中的继承
class Child extends Parent {
constructor(y) {
super(200)
this.y = y
}
getY() {
console.log(this.y)
}
}
const child = new Child(100)
console.log(child.x) // 成功访问父类属性
child.getX() // 成功调用父类方法
复制代码