1.ES5中的继承
(JS继承的几种方式,挖个坑,待填)
function Food() {
this.type = 'food'
}
Food.prototype.getType = function() {
return this.type
}
function Vegetables(name) {
this.name = name
}
// Vegetables继承Food
Vegetables.prototype = new Food()
const tomato = new Vegetables('tomato')
console.log(tomato.getType())
2.ES6中Class继承
class Parent {
constructor(name) {
this.name = name
}
getName() {
return this.name
}
static getNames() {
return `Inner ${this.name}`
}
}
class Child extends Parent {
constructor(name, age) {
super(name) // 子类必须调用super函数 之后才能使用this
this.age = age
}
}
const c = new Child('dan', 3)
console.log(c)
console.log(c.getName())
console.log(c instanceof Child) // true
console.log(c instanceof Parent) // true
console.log(Child.getNames()) // Inner Child
console.log(Parent.getNames()) // Inner Parent
// console.log(c.getNames()) // undefined 该static方法不被继承
3.Object.getPrototypeOf() 获取原型对象
console.log(Object.getPrototypeOf(Child) === Parent) // true
4. super
- super作为函数,代表父类的构造函数constructor。
子类继承时constructor里需要调用super()函数,super()中的传参和父类constructor中的传参一样。
- super作为对象
普通方法中,指向的是父类的原型对象
static静态方法中,指向的是父类
class Parent2 {
constructor() {
this.type = 'Parent'
}
getName() {
return this.type
}
}
Parent2.getType = () => {
return 'is Parent'
}
class Child2 extends Parent2 {
constructor() {
super()
console.log('constructor ' + super.getName())
}
getParentName() {
console.log('getParentName ' + super.getName())
}
getParentType() {
console.log('getParentType ' + super.getType())
}
static getParentType2() {
console.log('getParentType ' + super.getType())
}
}
const cc = new Child2() // constructor Parent
cc.getParentName() // getParentName Parent
// cc.getParentType() // super指向的是父类的原型对象,getType()定义在父类上,无法访问
Child2.getParentType2() // getParentType is Parent static静态方法,super指向父类,可以访问getType()
// 在父类的原型上定义方法,方法里的this指向子类的实例
class Parent3 {
constructor() {
this.name = 'parent'
}
print() {
console.log(this.name)
}
}
class Child3 extends Parent3 {
constructor() {
super()
this.name = 'child'
}
childPrint() {
super.print()
}
}
// super只能 1.作为函数使用 2.作为对象,调用上面的方法或属性
const d = new Child3()
d.childPrint()
5.类中的prototype属性和__proto__属性
var obj = new Object()
console.log(obj.__proto__ === Object.prototype) // true
// 子类的__proto__指向的是父类本身
// 子类的prototype属性的__proto__指向的是父类的prototype属性
// 实例的__proto__属性的__proto__指向的是父类实例的__proto__
6. ES6 原生构造函数的继承
原生构造函数 Boolean Number String Array Date Function RegExp Error Object
ES5中无法继承 ES6可继承
// ES6 原生构造函数的继承
class CustomArray extends Array {
constructor(...args) {
super(...args)
}
}
const arr = new CustomArray(3, 3, 1, 9, 7)
console.log(arr) // 长度为3的空数组
// console.log(arr.fill('+')) // ['+', '+', '+']
console.log(arr.join('_')) // +_+_+
open day + salary day