当前位置: 动力学知识库 > 问答 > 编程问答 >

Why does the following javascript throw a TypeError?

问题描述:

Executing

var q = document.querySelector;

q("div");

throws a TypeError: Illegal Invocation exception. Why is that?

网友答案:

because the querySelector method requires an instance of document to work on. you can call

q.call(document, "div")

Which says run the method, with this = document

To elaborate, the reason you are getting the error is because if you don't use the above syntax 'this' inside that function will refer to 'window'. The function must have some form of checking to ensure that 'this' is of type document.

分享给朋友:
您可能感兴趣的文章:
随机阅读: