Is it possible to assign a native function to a variable?

4

A hypothetical example ...

let _ = document.querySelector;

_(".hello").style.color = 'blue';
<div class="hello">Hello world!</div>
    
asked by anonymous 11.09.2018 / 21:18

1 answer

5

In Javascript, JavaScript object methods have a context. When you use some native object and attempt to assign a method of this to a variable, to call it later, you will receive an Illegal Invocation . This is because this function will lose the original context that was assigned to it and will default to the global context, which in this case is window , as read in that response from SOEN.

To solve this, you must explicitly inform the context in which the function will be called, using the bind method.

let _ = document.querySelector.bind(document);

_(".hello").style.color = 'blue';
<div class="hello">Olá, mundo</div>

The context of querySelector is document . Therefore, when you assign the value of the method to a variable, you must enter it using bind .

Another (less elegant) way would be to use the call method:

  _.call(document, ".hello").style.color = "red"

Or use an anonymous function or arrow function to solve the problem:

let _ = (...args) => document.querySelector(...args);

_(".hello").style.color = 'blue';
<div class="hello">Olá, mundo</div>

I will not stretch too much, because I think it has part of the explanation here:

11.09.2018 / 21:23