'Illegal invocation with document.querySelector [duplicate]
Possible Duplicate:
JavaScript function aliasing doesn't seem to work
Related jsfiddle: http://jsfiddle.net/cWCZs/1/
The following code works perfectly:
var qs = function( s ) {
return document.querySelector( s );
};
qs( 'some selector' );
But the following doesn't:
var qs = document.querySelector;
qs( 'some selector' ); // Uncaught TypeError: Illegal invocation
I don't understand why.
My confusion comes with the fact that this works:
function t() {
console.log( 'hi' );
}
var s = t;
s(); // "hi"
Solution 1:[1]
The problem lies in the this value.
//in the following simile, obj is the document, and test is querySelector
var obj = {
test : function () {
console.log( this );
}
};
obj.test(); //logs obj
var t = obj.test;
t(); //logs the global object
querySelector is not a generic method, it will not accept another this value. So, if you want a shortcut, you must make sure your querySelector is bound to the document:
var qs = document.querySelector.bind( document );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zirak |
