javascript - 文档方法引用在 JavaScript 中不起作用
问题描述
我保存了文档方法的引用:
let qs = document.querySelector;
然后尝试获取元素:
btnSort = qs('button');
为什么这种方法不适用于对简单函数的引用?
解决方案
因为this
在 JavaScript 中是在运行时确定的。
document.querySelector(...) // this -> document
let qs = document.querySelector
qs(...) // In this case `this` refer to the global object, which is window in a browser
您需要this
在创建函数引用时进行绑定。
let qs = document.querySelector.bind(document)
或者在你调用它时给出一个 this 绑定。
qs.call(document, 'button')
推荐阅读
- ios - IOS 应用程序因“bug_type”而崩溃:“179”
- mysql - 尝试将 txt 文件插入 MySql 时出现 MySql 错误 1054
- reactjs - Flow 给出错误“无法将 [value] 分配给 this.[property],因为 [class] 中缺少属性 [property]”
- c# - 使用 VSCode 和 .NET Core 设置 xUnit 时出现问题,如何正确设置?
- three.js - 三个 Js BufferGeometry Loader 给了我一个“Uncaught TypeError: Cannot read property 'index' of undefined”为什么?
- sockets - TCP 套接字可能会中断以使其仍在接收但不能再发送?
- javascript - 如何使用相同的 script.js 文件使用多个 Id 调用不同的 CSS 类
- hyperledger-fabric - 在超级账本 Composer 中自动执行交易
- python - While 循环请求分页链接
- javascript - Angular 或 JS 动态变量指针名称