为了方便调用querySelector方法,我很自然的写下来这样的代码:
let $ = document.querySelector;
$('a'); // Uncaught TypeError: Illegal invocation
然后就报错了。
参考了一些文章之后发现这就是this指向的问题,querySelector的内部实现依赖于(this)document,因此我们手动绑定一下就好了。
let $ = document.querySelector.bind(document)
Reference
https://stackoverflow.com/questions/12637061/illegal-invocation-with-document-queryselector
5703

被折叠的 条评论
为什么被折叠?



