What is the meaning of document.querySelector.bind(document);
Asked Answered
G

2

6

I was checking this code from html5rocks: http://www.html5rocks.com/static/demos/parallax/demo-1a/scripts/parallax.js

And notice that they use

(function(win, d) {

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

  ....

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

  ....

})(window, document);

Why they bind the document to the querySelector. Isn't it already scoped to the document?

Ghee answered 10/1, 2013 at 5:28 Comment(1)
This answer has further explanation. Short answer: JavaScript interpreter throws an error because querySelectorAll() should be invoked in document context.Serenaserenade
F
4

No, the function is not bound to a specific document (there may be other ones, not just window.document). Try it without, and you will get an WRONG_THIS_ERR exception - you will need to apply it on an object that implements the Document interface.

Also have a look on MDN's introduction to the this keyword on how the thisVal("context") of a function call is determined.

Ferguson answered 10/1, 2013 at 5:32 Comment(1)
Thank you. Let's assume we are not in "strict mode", in a browser, and we create a function: function a() { console.log(this); } if we call a(); the console print window. But it is like javascript prepend this. behind the scene this.a(); and this is the window context. For the same reason if we create a new object var o = {}; and we assign the a method o.a = a; and we run o.a(); the console print the o object. I know it might not be the proper explanation, but this "context" in javascript sometime is driving me nuts.Ghee
H
1

For future googlers, and as a side note, one can also use document.querySelector.bind(document) to make jQuery-like selections:

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

var $$ = document.querySelector.bind(document);
console.log( 'Ye Olde StackSnippet body: ', $$('body').textContent );
Hogfish answered 27/8, 2020 at 19:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.