English 中文(简体)
为什么在JavaScript中某些功能电话被称为“非法援引”?
原标题:Why are certain function calls termed "illegal invocations" in JavaScript?

例如,如果我这样做:

var q = document.querySelectorAll;

q( body );

在Chrome, 我有一个“ 非法援引” 错误。 我无法想到为什么有必要这样做。 首先, 并非所有本地代码功能都属于这种情况。 事实上, 我可以做到这一点 :

var o = Object; // which is a native code function

var x = new o();

一切都很好,特别是我在处理文件和控制台时发现了这个问题。有什么想法吗?

问题回答

这是因为你失去了函数的“通俗性”。

当你呼唤:

document.querySelectorAll()

函数的上下文为 document ,通过采用该方法,该函数将以 this 的形式作为 访问。

当您刚刚调用 >q 时, 不再有上下文 - 而是“ global” window 对象 。

执行 querySelectorAll 试图使用 this ,但它不再是 DOM 元素,它是一个 Window 对象。 执行试图调用在 < code> Window 对象上不存在的 DOM 元素的某些方法, 解释者毫不奇怪地称其为违法 。

要解决这个问题, 请使用 < code>. bind 来更新 Javascript 版本 :

var q = document.querySelectorAll.bind(document);

这将确保 >q 之后的所有引用都有正确的上下文。 如果您没有获得 . bind , 请使用 :

function q() {
    return document.querySelectorAll.apply(document, arguments);
}

您可以这样使用 :

let qsa = document.querySelectorAll;
qsa.apply(document,[ body ]);




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签