爲什麼document.querySelectorAll要bind(document)

前言

阮一峯老師提到的jquery-free

const $ = document.querySelectorAll.bind(document);

爲什麼要bind document對象?

如下的使用會報錯

const select = document.querySelectorAll;
select('div');

原因:this指向

自己的錯誤理解

我簡單的認爲,可以替換成這樣

const select = document.querySelectorAll;
select('div');
// 等價於
const select = document.querySelectorAll;
window.select('div');
// 等價於
window.document.querySelectorAll('div');

但是這個寫法是不會報錯的

window.document.querySelectorAll('div');

那麼問題在哪呢

正解

原來是我在上面不停等價轉換的時候出了問題

看一個例子

var a = {
    b: function test() {
        console.log(this);
    }
};
var c = a.b;
c();// 結果:this 指向 window
console.log(c);// c 就是 test函數

所以是window調用了c,故this指向window

回頭看看最初的問題

const select = document.querySelectorAll;
// document 就是 a對象
// querySelectorAll 就是 test函數
// select 就是 c變量
select('div');

這樣調用就是在window下掉用了querySelectorAll

而在window對象下是找不到各個標籤的

結論

const $ = document.querySelectorAll;
$('div');

這樣寫相當於在window對象下,查找標籤,是找不到的

發佈了39 篇原創文章 · 獲贊 8 · 訪問量 6312
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章