为什么某些函数调用被称为“非法调用”?在JavaScript? [英] Why are certain function calls termed "illegal invocations" in JavaScript?

查看:553
本文介绍了为什么某些函数调用被称为“非法调用”?在JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我这样做:

var q = document.querySelectorAll;

q('body');

我在Chrome中收到非法调用错误。我想不出为什么这是必要的任何理由。首先,并非所有本机代码功能都是如此。事实上,我可以这样做:

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?

推荐答案

这是因为你丢失了函数的上下文。

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

致电时:

document.querySelectorAll()

该函数的上下文是 document ,并且可以这个通过实施该方法。

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

当你只是打电话给 q 那里有不再是上下文 - 而是全局窗口对象。

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

querySelectorAll 尝试使用但它不再是DOM元素,它是 Window 宾语。实现尝试调用 Window 对象上不存在的DOM元素的某些方法,并且解释器不出所料地调用foul。

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.

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

To resolve this, use .bind in newer versions of Javascript:

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

这将确保所有后续的 q 有正确的背景。如果你还没有 .bind ,请使用:

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);
}

这篇关于为什么某些函数调用被称为“非法调用”?在JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆