25

可能重复:
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"
4

1 回答 1

54

问题在于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 );
于 2012-09-28T09:22:32.197 回答