__proto__
:隱式原型,prototype:顯示原型,二者全等(===)
原型鏈是用來查找引用類型的屬性方法的。
要查找某個屬性方法時,從當前位置開始,沿着原型鏈一級一級向上查找,找到了就執行對應操作;否則,繼續查找,直到Object.prototype.proto,為 null。
原型關系
-
每個class都有顯示原型prototype
-
每個實例都有隱式原型
__proto__
-
實例
__proto__
指向對應class的prototype
1.如何判斷一個變量是不是數組
使用 instanceof Array
2.手寫一個簡易的jQuery,考慮插件和擴展性
class jQuery { constructor(selector) { const result = document.querySelectorAll(selector) const length = result.length for (let i = 0; i < length; i++) { this[i] = result[i] console.log(result) } this.length = length this.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'))
3.class的原型本質,怎么理解
class 實際上是函數,可見class是語法糖。
-
獲取屬性xialuo.name或執行方法xialuo.sayhi時
-
現在自身屬性和方法尋找
-
如果找不到自動去
__proto__