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?

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
Fabrizio Giordano
  • 2,941
  • 4
  • 20
  • 16
  • [This answer](http://stackoverflow.com/questions/13383886/making-a-short-alias-for-document-queryselectorall) has further explanation. Short answer: JavaScript interpreter throws an error because querySelectorAll() should be invoked in document context. – Adrian Moisa Jun 19 '15 at 12:21

2 Answers2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 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. – Fabrizio Giordano Jan 10 '13 at 06:14
0

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 );
cssyphus
  • 37,875
  • 18
  • 96
  • 111