为什么某些函数调用在 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
Why are certain function calls termed "illegal invocations" in JavaScript?
提问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 this
by the implementation of that method.
函数的上下文是document
,并且可以this
通过该方法的实现来访问。
When you just call q
there's no longer a context - it's the "global" window
object instead.
当您只是调用时q
,不再有上下文 - 它是“全局”window
对象。
The implementation of querySelectorAll
tries to use this
but it's no longer a DOM element, it's a Window
object. The implementation tries to call some method of a DOM element that doesn't exist on a Window
object and the interpreter unsurprisingly calls foul.
querySelectorAll
尝试使用的实现this
不再是 DOM 元素,而是一个Window
对象。该实现尝试调用Window
对象上不存在的 DOM 元素的某些方法,并且解释器毫不奇怪地调用了 foul。
To resolve this, use .bind
in newer versions of Javascript:
要解决此问题,请.bind
在较新版本的 Javascript 中使用:
var q = document.querySelectorAll.bind(document);
which will ensure that all subsequent invocations of q
have 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.
在我的情况下,由于将未声明的变量作为参数传递给函数而发生非法调用。确保在传递给函数之前声明变量。