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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 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. – VLAZ Sep 18 '19 at 06:10

1 Answers1

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')
Jian
  • 3,118
  • 2
  • 22
  • 36