[英]Illegal invocation for a method assignation
Why did i get an this kind of Error ? 为什么会出现这种错误? Basically, I can short my code like this.
基本上,我可以这样缩短我的代码。
const log = console.log;
So why can't we have this one? 那么为什么我们不能拥有这个呢?
const _search = document.querySeletor;
querySelector
can be called on many things, not just the document
, for example: 可以在很多东西上调用
querySelector
,而不仅仅是document
,例如:
const outer = document.querySelector('#outer'); const inner = outer.querySelector('div'); // querySelector called on `outer` console.log(inner);
<div id="outer"> <div id="inner"> </div> </div>
The querySelector
method must have a root element from which to search from, which it identifies by the calling context of the function (the this
value used inside it). querySelector
方法必须具有要从中进行搜索的根元素,该元素通过函数的调用上下文(在this
函数内部使用的this
值)进行标识。 In the above snippet, outer.querySelector('div')
selects a div
element which is a child of outer
. 在上面的代码中,
outer.querySelector('div')
选择一个div
元件,其的子outer
。 Simiarly, with document.querySelector
, you select a child anywhere in the document (but not, for example, in elements that exist, but are not attached to the document). 同样,通过
document.querySelector
,您可以在文档中的任意位置选择一个子级(例如,不选择存在于元素中但未附加到文档中的元素)。
But without a calling context (eg, if you assign querySelector
to a standalone variable), the method does not know what root element to search from, so it throws an error. 但是在没有调用上下文的情况下(例如,如果将
querySelector
分配给独立变量),该方法不知道要从哪个根元素进行搜索,因此会引发错误。
You can shorten it by .bind
ing the function to the document first, so that it has the appropriate calling context when invoked: 您可以通过将函数首先
.bind
到文档来缩短它,以便在调用时具有适当的调用上下文:
const qs = document.querySelector.bind(document); console.log(qs('#inner'));
<div id="outer"> <div id="inner"> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.