Why are certain function calls termed “illegal invocations” in JavaScript?

99封情书 提交于 2019-11-26 08:09:57

问题


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:

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?


回答1:


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.

When you just call q there's no longer a context - it's the "global" window object instead.

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.

To resolve this, use .bind in newer versions of 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:

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



回答2:


you can use like this :

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



回答3:


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



来源:https://stackoverflow.com/questions/10743596/why-are-certain-function-calls-termed-illegal-invocations-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!