|                              
 原型链在ES6中引入了class关键字,但是JS依然是基于原型的,class实际上是语法糖。
  举个例子,有一个people class: class People {  constructor(props) {    this.name = props.name;  }  run() {    console.log('run')  }}通过new people 这个class 产生了许多的人,张三,李四: let lisi = new People('李四')但是茫茫人海中,有一类人天赋异禀,他们这类人叫做超级英雄 class Hero class Hero extends People {   constructor(props) {    super(props);    this.power = props.power   }   heyHa() {       alert(this.power)   }}class Hero 继承了 People,所以英雄首先是个人,具有run方法,然后Hero具备普通人不具备的超能力heyHa方法。我们可以定义有一个英雄叫做Jinx,具有cannon的超能力: let Jinx = new Hero({ name: 'jinx', power: 'cannon!' })尽管实例Jinx没有定义run方法,但是通过原型链可以查找到People的原型上具有这个run方法,即它的隐式原型__proto__指向构造函数的原型  
 当实例访问某个方法或属性时,会从自身开始,然后往原型链上回溯查找 Jinx.heyHa() // cannon!// 当自身有该方法时Jinx.run = () => console.log('i just fly!')Jinx.run() // i just fly!那么People.prototype.__proto__指向哪里呢?Object.prototype, 在控制台中输入代码可以看到:  
 而Object.prototype的__prototype__ 等于 null,宇宙的尽头是虚无。。  
 至此完整的原型链图就是这样的:
   
 
 我们可以基于原型链来实现一个简易的JQuery库class JQuery {  constructor(selector, nodeList) {    const res = nodeList || document.querySelectorAll(selector);    const length = res.length;    for (let i = 0; i < length; i++) {      this[i] = res[i]    }    this.length = length;    this.selector = selector;  }  eq(index) {    return new JQuery(undefined, [this[index]]);  }  each(fn) {    for(let i = 0; i < this.length; i ++) {      const ele = this[i]      fn(ele)    }    return this;  }  on(type, fn) {    return this.each(ele => {      ele.addEventListener(type, fn, false)    })  }  // 扩展其他 DOM API}const $$ = (selector) => new JQuery(selector);$$('body').eq(0).on('click', () => alert('click'));在控制台中运行一下,结果如下:  
 
 总结
 本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注51zixue.net的更多内容!                                                          下载地址: JS实现课程表小程序(仿超级课程表)加入自定义背景功能 JavaScript数组方法实例详解 |