可能的重复项:
JavaScript 函数别名似乎不起作用
相关 jsfiddle: http://jsfiddle.net/cWCZs/1/
以下代码完美运行:
var qs = function( s ) {
return document.querySelector( s );
};
qs( 'some selector' );
但以下情况并非如此:
var qs = document.querySelector;
qs( 'some selector' ); // Uncaught TypeError: Illegal invocation
我不明白为什么。
我的困惑来自于这个有效的事实:
function t() {
console.log( 'hi' );
}
var s = t;
s(); // "hi"
问题在于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
不是泛型方法,它不会接受另一个this
值。因此,如果您想要快捷方式,则必须确保您的querySelector
绑定到文档:
var qs = document.querySelector.bind( document );