【问题标题】:What is the meaning of document.querySelector.bind(document);document.querySelector.bind(document) 是什么意思;
【发布时间】:2020-08-28 03:05:43
【问题描述】:

我正在检查 html5rocks 中的这段代码: http://www.html5rocks.com/static/demos/parallax/demo-1a/scripts/parallax.js

并注意他们使用

(function(win, d) {

  var $ = d.querySelector.bind(d);

  ....

  var mainBG = $('section#content');

  ....

})(window, document);

为什么他们将文档绑定到 querySelector。不是已经限定在文档范围内了吗?

【问题讨论】:

  • This answer 有进一步的解释。简短回答:JavaScript 解释器抛出错误,因为 querySelectorAll() 应该在文档上下文中调用。

标签: javascript bind document parallax.js


【解决方案1】:

不,the function 未绑定到特定文档(可能还有其他文档,而不仅仅是 window.document)。不试一试,你会得到一个WRONG_THIS_ERR 异常——你需要将它应用到一个实现Document interface 的对象上。

还可以查看MDN's introduction to the this keyword,了解如何确定函数调用的thisVal("context")。

【讨论】:

  • 谢谢。假设我们不在“严格模式”下,在浏览器中,我们创建一个函数:function a() { console.log(this); },如果我们调用a();,控制台打印window。但这就像 javascript 在幕后添加 this. this.a(); 一样,这是窗口上下文。出于同样的原因,如果我们创建一个新对象 var o = {}; 并分配 a 方法 o.a = a; 并运行 o.a(); 控制台打印 o 对象。我知道这可能不是正确的解释,但 javascript 中的这个“上下文”有时让我发疯。
【解决方案2】:

对于未来的谷歌用户,作为旁注,也可以使用document.querySelector.bind(document) 进行类似 jQuery 的选择:

var $$ = document.querySelector.bind(document);
console.log( $$('#answers').textContent );

var $$ = document.querySelector.bind(document);
console.log( 'Ye Olde StackSnippet body: ', $$('body').textContent );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2011-08-12
    • 2017-06-11
    • 2018-03-05
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多