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

Asked

Viewed 55 times

4

A hypothetical example...

let _ = document.querySelector;

_(".hello").style.color = 'blue';
<div class="hello">Hello world!</div>

1 answer

5


In javascript, object methods in Javascript have a context. When you use some native object and try to assign a method like this to a variable, to call it later, you will receive a Illegal Invocation. This is because this function will lose the original context assigned to it and will receive by default the global context, which in this case is window, as read in this reply of SOEN.

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

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

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

The context of querySelector is document. Therefore, when assigning the value of the method to a variable, it is necessary to inform through the bind.

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

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

Or use an anonymous function or Arrow funcion to solve the problem:

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

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

I’m not going to go too far, because I think there’s part of the explanation here:

  • Thanks for the answer! but I have one more question, let’s say I want to use querySelector without Document, for example _("#myDiv"). querySelector("input"); in the code next to querySelector would work as a jquery find, and I use a lot in my project, I would know how to bind it as well?

  • I don’t think I understand it very well. I could leave an example?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.