網站首頁 前端文檔 正文
原型鏈
在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'));
在控制臺中運行一下,結果如下:
總結
原文鏈接:https://blog.csdn.net/gsnmtorrent/article/details/122226692
相關推薦
- 2023-04-07 C#中括號強轉、as、is區別詳解_C#教程
- 2022-07-13 nginx-1.20*安裝check模塊
- 2022-07-20 基于Python操作Excel實戰案例
- 2023-08-15 .sync 父組件給子組件傳值 子組件修改父組件方法
- 2022-05-22 nginx共享內存的機制詳解_nginx
- 2022-12-07 C++中的類成員函數當線程函數_C 語言
- 2022-08-07 shell進度條追蹤指令執行時間的場景分析_linux shell
- 2022-04-28 python導入導出redis數據的實現_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支