我将大量运行document.querySelectorAll(),并且想要一个速记别名。
var queryAll = document.querySelectorAll
queryAll('body')
TypeError: Illegal invocation
给document.querySelectorAll起一个queryAll的别名,调用时会报错。提示错误:非法调用。
原因如下:
The JavaScript interpreter throws an error because querySelectorAll() should be invoked in document context.
因为querySelectorAll方法是需要在document元素上下文环境下才能被调用。
如何使别名起作用?你就该使用bind:
var queryAll = document.querySelectorAll.bind(document);
bind
returns a reference to the querySelectorAll
function, changing the context of ‘this’ inside the querySelectorAll method to be the document object.
绑定功能仅在IE9 +(和所有其他浏览器)中受支持-https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Function/bind
更新:实际上,您可以为整个文档方法创建快捷方式,如下所示:
var query = document.querySelector.bind(document);
var queryAll = document.querySelectorAll.bind(document);
var fromId = document.getElementById.bind(document);
var fromClass = document.getElementsByClassName.bind(document);
var fromTag = document.getElementsByTagName.bind(document);
参考资料