首页 > 解决方案 > 文档方法引用在 JavaScript 中不起作用

问题描述

我保存了文档方法的引用:

let qs = document.querySelector;

然后尝试获取元素:

btnSort = qs('button');

为什么这种方法不适用于对简单函数的引用?

标签: javascriptdom

解决方案


因为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')

推荐阅读