为什么某些函数调用在 JavaScript 中被称为“非法调用”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10743596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:45:20  来源:igfitidea点击:

Why are certain function calls termed "illegal invocations" in JavaScript?

javascriptinvocation

提问by user1152187

For example, if I do this:

例如,如果我这样做:

var q = document.querySelectorAll;

q('body');

I get an "Illegal invocation" error in Chrome. I can't think of any reason why this is necessary. For one, it's not the case with all native code functions. In fact I can do this:

我在 Chrome 中收到“非法调用”错误。我想不出有什么必要这样做。一方面,并​​非所有本机代码函数都如此。事实上,我可以这样做:

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

var x = new o();

And everything works just fine. In particular I've discovered this problem when dealing with document and console. Any thoughts?

一切正常。特别是我在处理文档和控制台时发现了这个问题。有什么想法吗?

回答by Alnitak

It's because you've lost the "context" of the function.

这是因为你已经失去了函数的“上下文”。

When you call:

你打电话时:

document.querySelectorAll()

the context of the function is document, and will be accessible as thisby the implementation of that method.

函数的上下文是document,并且可以this通过该方法的实现来访问。

When you just call qthere's no longer a context - it's the "global" windowobject instead.

当您只是调用时q,不再有上下文 - 它是“全局”window对象。

The implementation of querySelectorAlltries to use thisbut it's no longer a DOM element, it's a Windowobject. The implementation tries to call some method of a DOM element that doesn't exist on a Windowobject and the interpreter unsurprisingly calls foul.

querySelectorAll尝试使用的实现this不再是 DOM 元素,而是一个Window对象。该实现尝试调用Window对象上不存在的 DOM 元素的某些方法,并且解释器毫不奇怪地调用了 foul。

To resolve this, use .bindin newer versions of Javascript:

要解决此问题,请.bind在较新版本的 Javascript 中使用:

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

which will ensure that all subsequent invocations of qhave the right context. If you haven't got .bind, use this:

这将确保所有后续调用q具有正确的上下文。如果你还没有.bind,请使用这个:

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

回答by love-for-coding

you can use like this :

你可以这样使用:

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

回答by BenVida

One more concise solution:

一种更简洁的解决方案:

const q=s=>document.querySelectorAll(s);
q('body');

回答by Fawad

In my case Illegal invocation occurred due to passing undeclared variable to function as argument. Make sure to declare variable before passing to function.

在我的情况下,由于将未声明的变量作为参数传递给函数而发生非法调用。确保在传递给函数之前声明变量。