0

I save the reference of document method:

let qs = document.querySelector; 

Then try to get the element:

btnSort = qs('button'); 

Why does this method not work as for references to simple functions?

1
  • 1
    Because you lose the context. querySelector can be invoked from different elements, not just document, so it relies on this. When you reassign the reference and invoke the new variable, you lose the this context. Commented Sep 18, 2019 at 6:10

1 Answer 1

1

Because this in JavaScript is determined in runtime.

document.querySelector(...) // this -> document let qs = document.querySelector qs(...) // In this case `this` refer to the global object, which is window in a browser 

You need to bind this when you created a function reference.

let qs = document.querySelector.bind(document) 

Or giving a this binding when you call it.

qs.call(document, 'button') 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.