一、class 和 继承
1. 基本实现
class的核心:constructor、属性、方法。继承的核心:extends、super、扩展或重写方法。
<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial=1.0"><title>class和继承</title></head><body><script>// 父类class People {constructor(name) {this.name = name}eat() {console.log(`${this.name} 吃东西`);}}// 子类--学生类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 xialuo = new Student('夏洛', 100)console.log(xialuo.name)console.log(xialuo.number)xialuo.sayHi()xialuo.eat()// 实例const wanglaoshi = new Teacher('王老师', '语文')console.log(wanglaoshi.name)console.log(wanglaoshi.major)wanglaoshi.teach()wanglaoshi.eat()</script></body></html>
详细说明链接:Class 类_小豪boy的博客-CSDN博客_class
2.class的原型本质,怎么理解?
class是ES6语法规范,由ECMA委员会发布。ECMA只规定语法规则,即我们代码的书写规范,不规定如何实现。以上实现方式都是V8引擎的实现方式,也是主流的。
3. class 的应用,手写一个简易的jQuery,考虑插件和扩展性
简易的jQuery
class jQuery {constructor(selector) {const result = document.querySelectorAll(selector)const length = result.lengthfor (let i = 0; i < length; i++) {this[i] = result[i]}this.length = lengththis.selector = selector}get(index) {return this[index]}each(fn) {for (let i = 0; i< this.length; i++) {const elem = this[i]fn(elem)}}on(type, fn) {return this.each(elem => {elem.addEventListener(type, fn, false)})}}
插件
// 插件jQuery.prototype.dialog = function (info) {alert(info)}
扩展性--“造轮子”
// “造轮子”class myJQuery extends jQuery {constructor(selector) {super(selector)}// 扩展自己的方法addClass(className) {}style(data) {}}
二、类型判断 instanceof
三、原型和原型链
1. 原型关系
class 实际上是函数,可见是语法糖,具体实现还是使用的原型与原型链。隐世原型(__proto__)和显示原型(prototype)。每个 class都有显示原型prototype。每个实例都有隐式原型__proto__。实例的__proto__指向对应 class 的prototype 。
2. 基于原型的执行规则
获取实例的属性或执行方法时,先在自身属性和方法中寻找,如果找不到则自动去隐式原型 __proto__中查找,若还是没有找到,则逐级向上查找,当查找到目标或隐式原型 __proto__ 为 null 时,结束查找。