Skip to content Skip to sidebar Skip to footer

Why We Can't Assign Document.queryselector Method To Another Variable And Use It?

As we know we can assign a function/method to another variable and execute it anytime with the assigned variable. But why we can't assign document.querySelector to a variable and

Solution 1:

querySelector requires that it is bound to the instance of the document class. It checks for this internally. When assigning to a variable outside the scope of its owning class, it’s unable to perform the necessary logic of querying against the document instance to which it should belong.

This can be forced, by binding the method to the document instance:

const querySelector = document.querySelector.bind(document)

The above will bind references to this from within the querySelector method to reference the document instance on subsequent calls, regardless of the fact it is at this point a standalone function in the global scope.

You can see a similar loss of ‘this’ scope in your logger class with the following:

const logger = {
  log: function() {
    console.log(this.toString());
  },
};

const log = logger.log;
logger.log(); // [object Object] (the logger object)log(); // [object Window] (the global object)

Solution 2:

Try in this way:

const myDocument = document.querySelector.bind(document);
myDocument("body");

Post a Comment for "Why We Can't Assign Document.queryselector Method To Another Variable And Use It?"