JS前端面试基础-原型和原型链


JS是基于原型集成的语言
题目引入
1.如何判断一个变量是不是数组
2.Class的原型本质,如何理解?

知识点
Class和继承
类型判断和instanceof
原型和原型链

一、class和继承

1.Class(类)
Constructor: 声明属性
属性和方法
在这里插入图片描述
2.继承
Extends
Super 继承父类属性
子类可以扩展或重写方法

// 父类
class People {
    constructor(name) {
        this.name = name
    }
    eat() {
        console.log(`${this.name} eat something`)
    }
}
//子类
class Student extends People {
    constructor(name,number) {
        super(name)
        this.number = number
    }
    sayHi() {
        console.log(`姓名:${this.name},学号:${this.number}`)
    }
}
//子类
class Teacher extends People {
    constructor(name,major) {
        super(name)
        this.major = major
    }
    teach() {
        console.log(`${this.name} 教 ${this.major}`)
    }
}
//创建实例
const whl = new Student('whl',1)
console.log(whl.name)
console.log(whl.number)
whl.sayHi()
whl.eat() 

//创建实例
const whl1 = new Teacher('whl','数学')
console.log(whl1.name)
console.log(whl1.major)
whl1.teach()
whl1.eat()

输出的所有结果如下
在这里插入图片描述

二、类型判断和instanceof

1.instanceof可以判断引用类型(父子关系)
2.Object可以认为是所有class的父类

console.log(whl instanceof Student) // true
console.log(whl instanceof Object) // true
console.log([] instanceof Array) // true
console.log([] instanceof Object) //true
console.log({} instanceof Object) //true

三、原型

//class实际上是函数
console.log(typeof People) //function
console.log(typeof Student) //function
console.log(typeof Teacher) //funciton

重点
在这里插入图片描述
这些在页面的输出如下
在这里插入图片描述
1.关于原型的图解
在这里插入图片描述
文字解释: 在如上代码中我定义的是Student类,定义时会有一个函数,包含一个显示原型指向Student.prototype,并把sayHi()放进去,通过new Student生成对象whl之后,whl的属性name和number会直接放在对象里,然而方法sayHi()是通过__proto__(也就是隐式原型)来指向显示原型获取的

2.原型关系

1.每一个class定义后都有一个显示原型prototype
2.每个实例都有隐式原型__proto__
3.实例的__proto__指向对应class的prototype

3.基于原型的执行规则

获取whl.name时执行方法sayHi()时
首先在自身属性和方法寻找
如果没有则自动去__proto__中去寻找

四、原型链

console.log(Student.prototype.__proto__)
console.log(People.prototype)
console.log(Student.prototype.__proto__ === People.prototype) //true

输出结果如下
在这里插入图片描述
1.原型图解

在这里插入图片描述

console.log(whl.hasOwnProperty('name')) // true
console.log(whl.hasOwnProperty('sayHi')) //false

在这里插入图片描述
2.通过此图理解instanceof

顺着隐式原型往上找,看是否能找到显示原型,如果可以找到则instanceof是成立的

五、重要提示

1.Class是ES6语法规范,由ECMA委员会发布
2.ECMA只规定语法规则,即我们代码的书写规范,不规定如何实现
3.以上实现方式都是V8引擎的实现方式,也是主流的

六、题目解答

1.如何判断一个变量是不是数组?

可以使用 a instanceof Array(可以参考我之前写的深拷贝函数代码)

2.Class的原型本质,如何理解?

1.最好可以自己单独画出原型和原型链的图示
2.理解属性和方法的执行规则

七、小结

1.class和继承
2.instanceof
3.原型和原型链:最好可以画出图示,并且理解其方法和属性的执行规则

发布了16 篇原创文章 · 获赞 36 · 访问量 2388

猜你喜欢

转载自blog.csdn.net/m0_46269977/article/details/105583221