2012-09-28 11 views
11

Powiel możliwe:
JavaScript function aliasing doesn't seem to workNielegalne inwokacja z document.querySelector

Powiązane jsfiddle: http://jsfiddle.net/cWCZs/1/

Poniższy kod działa perfekcyjnie:

var qs = function(s) { 
    return document.querySelector(s); 
}; 
qs('some selector'); 

Ale następujące nie:

var qs = document.querySelector; 
qs('some selector'); // Uncaught TypeError: Illegal invocation 

Nie rozumiem dlaczego.

Moja dezorientacja pochodzi z faktu, że to działa:

function t() { 
    console.log('hi'); 
} 
var s = t; 
s(); // "hi" 

Odpowiedz

21

Problem polega na wartości this.

//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 nie jest sposób ogólny, że nie będzie akceptować inną wartość this. Tak więc, jeśli chcesz skrótu, należy upewnić się, że querySelector jest związany z dokumentem:

var qs = document.querySelector.bind(document); 
+1

Och, to jest lepsze rozwiązanie niż dwóch egzemplarzach. –

Powiązane problemy