當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
(五)JS基础知识二(通过图理解原型和原型链)【三座大山之一,必考!!!】
生活随笔
收集整理的這篇文章主要介紹了
(五)JS基础知识二(通过图理解原型和原型链)【三座大山之一,必考!!!】
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JS基礎(chǔ)知識(shí)二(原型和原型鏈)
- 提問(wèn)
- class
- 繼承
- 類型判斷(instanceof)
- 原型
- 原型關(guān)系
- 基于原型的執(zhí)行規(guī)則
- 原型鏈
- 說(shuō)明
提問(wèn)
- 如何準(zhǔn)確判斷一個(gè)變量是不是數(shù)組
- class的原型本質(zhì)
- 手寫簡(jiǎn)易jQuery考慮插件和擴(kuò)展性
class
class是一個(gè)類,相當(dāng)于模板,可以new一個(gè)類得到對(duì)象/實(shí)例
包含constructor、屬性、方法
// 類 class Student {constructor(name, number) {this.name = namethis.number = number}sayHi() {console.log(`姓名 ${this.name} ,學(xué)號(hào) ${this.number}`)} } // class是一個(gè)類,相當(dāng)于模板,可以new一個(gè)類得到對(duì)象/實(shí)例 // 通過(guò)類 new 對(duì)象/實(shí)例 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:執(zhí)行父類的構(gòu)造函數(shù)、構(gòu)建過(guò)程
- 擴(kuò)展或重寫方法
擴(kuò)展或重寫方法
//手寫簡(jiǎn)易jQuery考慮插件和擴(kuò)展性 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)})}// 擴(kuò)展很多 DOM API }// 插件 jQuery.prototype.dialog = function (info) {alert(info) }// “造輪子” class myJQuery extends jQuery {constructor(selector) {super(selector)}// 擴(kuò)展自己的方法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)
判斷變量屬于哪個(gè)class,屬于哪個(gè)構(gòu)造函數(shù)
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實(shí)際上是函數(shù),可見(jiàn)是語(yǔ)法糖
- hasOwnProperty 判斷是不是自己的屬性
- 隱式原型(proto ),顯式原型(prototype)
原型關(guān)系
- 每個(gè)class都有顯式原型prototype
- 每個(gè)實(shí)例都有隱式原型__proto__
- 實(shí)例的__proto__指向?qū)?yīng)class的prototype
基于原型的執(zhí)行規(guī)則
- 獲取屬性xialuo.name 或 執(zhí)行方法xialuo.saiHi()時(shí)
- 先在自身屬性和方法查找
- 如果找不到則自動(dòng)去__proto__中查找
原型鏈
People.prototype === Student.prototype.__proto__instanceof判斷技巧:順著變量的隱式原型一直往上找,看能不能對(duì)應(yīng)到class的顯式原型,能instanceof成立,不能返回false
說(shuō)明
- class是ES6語(yǔ)法規(guī)范,由ECMA委員會(huì)發(fā)布
- ECMA只規(guī)定語(yǔ)法規(guī)則,即我們代碼的書(shū)寫規(guī)范,不規(guī)定如何實(shí)現(xiàn)
- 以上實(shí)現(xiàn)方式都是v8引擎的實(shí)現(xiàn)方式,也是主流的
總結(jié)
以上是生活随笔為你收集整理的(五)JS基础知识二(通过图理解原型和原型链)【三座大山之一,必考!!!】的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 3-unit9 apache
- 下一篇: (六)JS基础知识三(走进作用域和闭包)