【问题标题】:Illegal invocation with document.querySelector [duplicate]非法调用 document.querySelector [重复]
【发布时间】:2012-09-20 03:56:59
【问题描述】:

可能重复:
JavaScript function aliasing doesn't seem to work

相关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"

【问题讨论】:

    标签: javascript dom


    【解决方案1】:

    问题在于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 );
    

    【讨论】:

    • 哦,那是比复制更好的解决方案。
    猜你喜欢
    • 2021-09-24
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多