js面试必备知识,关注作者查看系列js知识体系
导语:不懂继承和原型链,是一个不合格的前端工程师!!!
1, class和继承
我们先来看一段代码
class person {
constructor(name, id) {
this.name = name
this.id = id
}
sayMyName() {
console.log(`我的名字是 ${this.name} `)
}
}
const xiaoming = new person('小明', 100)
console.log(xiaoming.name) // 小明
console.log(xiaoming.id) // 100
xiaoming.sayMyName() // 我的名字是小明
我相信这是很基础的东西,大家都懂。
我们再来说一下继承。
class person {
constructor(name) {
this.name = name
}
}
class Student extends person {
constructor(name,id) {
super(name)
this.id = id
}
sayMyID() {
console.log(`我的姓名是 ${this.name} 学号是 ${this.id}`)
}
}
const xiaoming = new Student('小明', 100)
xiaoming.sayMyID() // 我的姓名是小明 学号是100
2, 原型链
先来讲一讲原型,我们先引入一个instanceof,它能够判断是变量什么类型,能够判断跟某个class是否有关系。
xiaoming instanceof person // true
xiaoming instanceof Student // true
//
console.log(xiaoming.__proto__) //输出类似person的构造函数
console.log(Student.prototype) //输出类似person的构造函数
console.log(xiaoming.__proto__ === Student.prototype) //true
我们在使用对象的属性或者方法的时候,先会在这个实例里面查找有没有这个属性或者方法,如果找不到,那么它就会自动的往上找,也就是实例class继承的class里面找这个属性或者方法直到找到为止。所以我们不难发现,xiaoming.__ proto __=== Student.prototype,因为小明的 __ proto __指向他继承的student的prototype,这样一串有一串,就构成了我们的原型链。