27

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"
Community
  • 1
  • 1
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116

1 Answers1

60

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 );
Zirak
  • 38,920
  • 13
  • 81
  • 92