當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
(五)JS基础知识二(通过图理解原型和原型链)【三座大山之一,必考!!!】
生活随笔
收集整理的這篇文章主要介紹了
(五)JS基础知识二(通过图理解原型和原型链)【三座大山之一,必考!!!】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
JS基礎知識二(原型和原型鏈)
- 提問
- class
- 繼承
- 類型判斷(instanceof)
- 原型
- 原型關系
- 基于原型的執行規則
- 原型鏈
- 說明
提問
- 如何準確判斷一個變量是不是數組
- class的原型本質
- 手寫簡易jQuery考慮插件和擴展性
class
class是一個類,相當于模板,可以new一個類得到對象/實例
包含constructor、屬性、方法
// 類 class Student {constructor(name, number) {this.name = namethis.number = number}sayHi() {console.log(`姓名 ${this.name} ,學號 ${this.number}`)} } // class是一個類,相當于模板,可以new一個類得到對象/實例 // 通過類 new 對象/實例 const xialuo = new Student('夏洛', 100) console.log(xialuo.name) console.log(xialuo.number) xialuo.sayHi()const madongmei = new Student('馬冬梅', 101) console.log(madongmei.name) console.log(madongmei.number) madongmei.sayHi()繼承
- extends
- super:執行父類的構造函數、構建過程
- 擴展或重寫方法
擴展或重寫方法
//手寫簡易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)})}// 擴展很多 DOM API }// 插件 jQuery.prototype.dialog = function (info) {alert(info) }// “造輪子” class myJQuery extends jQuery {constructor(selector) {super(selector)}// 擴展自己的方法addClass(className) {}style(data) {} }// const $p = new jQuery('p') // $p.get(1) // $p.each((elem) => console.log(elem.nodeName)) // $p.on('click', () => alert('clicked'))類型判斷(instanceof)
判斷變量屬于哪個class,屬于哪個構造函數
xialuo instanceof Student //true xialuo instanceof People //true xialuo instanceof Object //truexialuo instanceof Array //false [] instanceof Array //true [] instanceof Object //true {} instanceof Object //true原型
- typeof People === ‘function’ //class實際上是函數,可見是語法糖
- hasOwnProperty 判斷是不是自己的屬性
- 隱式原型(proto ),顯式原型(prototype)
原型關系
- 每個class都有顯式原型prototype
- 每個實例都有隱式原型__proto__
- 實例的__proto__指向對應class的prototype
基于原型的執行規則
- 獲取屬性xialuo.name 或 執行方法xialuo.saiHi()時
- 先在自身屬性和方法查找
- 如果找不到則自動去__proto__中查找
原型鏈
People.prototype === Student.prototype.__proto__instanceof判斷技巧:順著變量的隱式原型一直往上找,看能不能對應到class的顯式原型,能instanceof成立,不能返回false
說明
- class是ES6語法規范,由ECMA委員會發布
- ECMA只規定語法規則,即我們代碼的書寫規范,不規定如何實現
- 以上實現方式都是v8引擎的實現方式,也是主流的
總結
以上是生活随笔為你收集整理的(五)JS基础知识二(通过图理解原型和原型链)【三座大山之一,必考!!!】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3-unit9 apache
- 下一篇: (六)JS基础知识三(走进作用域和闭包)