JavaScript继承机制: JavaScript是基于原型链继承的语言,当访问一个属性或者方法的时候,js会沿着原型链依次往上寻找,直到找到相关的值,或者查找到Object.proto === null, 返回undefined值。
有时候,可能需要我们自己去实现类之间的继承,下面是几种继承方法,从上往下,继承方式呈逐渐优化趋势。
父函数和子函数
// 父函数
function Person(sex) {
this.sex = sex
console.log(count++)
}
// 父函数原型链方法
Person.prototype.showSex = function () {
console.log(this.sex)
}
// 子函数
function People(name, age) {
this.name = name
this.age = age
}
// 子函数原型链方法
People.prototype.sayHi = function () {
console.log(`hi~, I am a ${this.sex === 'femal' ? 'girl': 'boy'} my name is ${this.name}, and I am ${this.age} years old`)
}
构造函数继承
function People(name, age) {
this.name = name
this.age = age
Person.call(this, 'femal')
}
不能继承父类的原型链方法,只能实现构造函数的继承
原型链继承
Person.prototype = new Person('femail')
// 添加子函数原型链方法
People.prototype.sayHi = function () {
console.log(`hi~, I am a ${this.sex === 'femal' ? 'girl': 'boy'} my name is ${this.name}, and I am ${this.age} years old`)
}
只能继承原型链上的继承,父类构造函数里的数据会丢失掉
组合继承
// 继承父类构造函数
function People(name, age) {
this.name = name
this.age = age
Person.call(this, 'femal')
}
// 继承父类原型链
Person.prototype = new Person('femail')
// 添加子函数原型链方法
People.prototype.sayHi = function () {
console.log(`hi~, I am a ${this.sex === 'femal' ? 'girl': 'boy'} my name is ${this.name}, and I am ${this.age} years old`)
}
同是继承了父类的构造函数和原型链,但是父类的构造函数实例化了两次,造成了不必要的消耗
寄生式继承
// 寄生式继承,通过一个中间值,实现子类原型对象向父类原型对象的指向
// supClass:Constructor 父类
// subClass: Constructor 子类
function inherite(supClass, subClass) {
let prop = Object.create(supClass).prototype
prop.constructor = subClass
subClass.prototype = prop
}
// 子类,完成构造函数的继承
function People(name, age) {
this.name = name
this.age = age
Person.call(this, 'femal')
}
完美!