1

In JavaScript, you can set variables to hold certain functions and use them, like so:

var log = console.log;
log('foo'); 

But for some strange reason, you can't do that on most if not all document methods, such as querySelector:

var select = document.querySelector;

// causes the error: Uncaught TypeError: Illegal invocation
select('p'); 
<p>...</p>

Why is that, and is there a workaround for it?

Mystical
  • 2,505
  • 2
  • 24
  • 43
  • 5
    Because of `this`. Try with `var select = document.querySelector.bind(document);`; https://stackoverflow.com/questions/2236747/use-of-the-javascript-bind-method – Federkun Dec 31 '18 at 19:00

1 Answers1

3

The context seems to get lost. It's not bound with the document. Use it this way:

var select = document.querySelector.bind(document);
// Works!
console.log(select('p'));
<p>...</p>

You can see what a function is bound to, in JavaScript: What object javascript function is bound to (what is its "this")?.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252