前端面试知识整理——JS基础原型和原型链
题目:
- 如何准确判断一个变量是不是数组
a instanceof Array - class的原型本质,怎么理解
原型和原型链的图示 属性和方法的执行规则
知识点:
- class 和集成
- 类型判断instanceof
- 原型和原型链
1 class
- construct
- 属性
- 方法
class Student {
constructor(name, number) {
this.name = name
this.number = number
}
sayHi() {
console.log(`name:${this.name},number:${this.number}`)
}
}
const xiaobai = new Student('xiaobai', 18)
xiaobai.sayHi()
2 继承
- extends
- super
- 扩展或重写
class Person {
constructor(name) {
this.name = name
}
eat() {
console.log(`name:${this.name}`)
}
}
class Student extends Person {
constructor(name, number) {
super(name)
this.number = number
}
sayHi() {
console.log(`name:${this.name},number:${this.number}`)
}
}
const xiaobai = new Student('xiaobai', 18)
xiaobai.eat()
xiaobai.sayHi()
3 类型判断-instanceof
instanceof:顺着隐式原型链向上找,如何能找到对应的显示原型,则为true
console.log(xiaobai instanceof Student) //true
console.log(xiaobai instanceof Person) //true
console.log(xiaobai instanceof Object) //true
[] instanceof Array //true
[] instanceof Object //true
{} instanceof Object //true
4 原型
规则:
- 每个class都有显示原型prototype
- 每个实例都有隐式原型__proto__
- 实例的隐式原型指向class 的显示原型
基于原型的的执行规则:
- 获取属性xiaobai.name或者xiaobai.sayHi()时
- 先在自身属性和方法寻找
- 如果找不到则自动去__proto__中查找
//class实际上是函数,可见是语法糖
console.log(typeof Student) //function
console.log(typeof Person) //function
//隐式原型 显示原型
console.log(xiaobai.__proto__ === Student.prototype) //true
5 原型链
//原型链
console.log(Person.prototype === Student.prototype.__proto__) //true