Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What does this trick do?


Written in older JS, it would look like this:

$ = function(_) { return document.querySelector(_) }

It basically turns `$` into an alias for `document.querySelector`. I'm not sure that it's any different from:

$ = document.querySelector


Sadly it is different because of the magic of this. If you set something equal to document.querySelector and then call it this will no longer refer to document. There are fancier ways with Function.prototype.bind, but wrapping in a function is the easiest conceptually.

https://www.taniarascia.com/this-bind-call-apply-javascript/

For this specific case, you can see this at https://stackoverflow.com/q/13383886/8334056


For posterity:

  $ = document.querySelector.bind(document);


Thank you




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: