6

我正在检查来自 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。它不是已经在文档范围内吗?

4

2 回答 2

4

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

还可以查看MDNthis对如何thisVal确定函数调用的(“上下文”)关键字的介绍。

于 2013-01-10T05:32:35.850 回答
0

对于未来的谷歌用户,作为旁注,也可以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 );

于 2020-08-27T19:05:43.253 回答