javascript - document.querySelectorAll赋给其它变量时, 为什么要.bind(document)?
本文介绍了javascript - document.querySelectorAll赋给其它变量时, 为什么要.bind(document)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
http://www.ruanyifeng.com/blo...
阮一峰的博客提到$的替代方法:
var $ = document.querySelectorAll.bind(document);
让我比较在意的是最后那个bind
按理说querySelectorAll
是作为document
的方法调用的, 执行上下文已经是document
了啊, 为什么还要再bind
一次呢?
比如: 执行如下代码:
var select = document.querySelectorAll;
select('span');
会报错
VM2761:1 Uncaught TypeError: Illegal invocation(…)
而
select.call(document, 'span');
就会得出正确结果了.
求解!~
解决方案
这个问题其实和querySelectorAll
没什么关系。document
是类的一个实例,而querySelectorAll
是原型链上的方法。
类比到普通的类和原型方法就很好理解了吧。
通过实例来运行原型链上的方法时,解释器会自动将this指向那个实例
但是直接这样var select = document.querySelectorAll;
,你的变量仅仅是指向了原型链上的那个函数,而没有绑定this指针,所以你才需要在外面手动绑定一下指针。
这篇关于javascript - document.querySelectorAll赋给其它变量时, 为什么要.bind(document)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文