javascript - 根据规范,JavaScript 中的所有对象都是真实的,但在 DOM 中,一个非原始对象不是。哪个?

标签 javascript dom object

this tweet on Twitter :

In JavaScript, all objects are truthy (as per the spec). In the DOM, there’s one exception to this rule. What is it? #jsquiz #fronttrends

有人知道答案吗?

最佳答案

免责声明: I’m the guy who tweeted that :)这是我会在 Front-Trends 中提出和回答的问题。讲话。我在上台前 5 分钟写了那条推文。


由于 Twitter 上有 140 个字符的限制,这个问题有点模棱两可。我问的真正问题如下。

ECMAScript 规范 defines ToBoolean() as follows :

ToBoolean(condition), slide from my Front-Trends 2012 talk

如您所见,所有非原始对象(即所有不是 bool 值、数字、字符串、undefinednull 的对象)都是按照规范真实。然而,在 DOM 中,有一个异常(exception)——DOM 对象是假的。你知道那是哪一个吗? 答案是 document.allThe HTML spec说:

The all attribute must return an HTMLAllCollection rooted at the Document node, whose filter matches all elements.

The object returned for all has several unusual behaviors:

The user agent must act as if the ToBoolean() operator in JavaScript converts the object returned for all to the false value.

The user agent must act as if, for the purposes of the == and != operators in JavaScript, the object returned for all is equal to the undefined value.

The user agent must act such that the typeof operator in JavaScript returns the string 'undefined' when applied to the object returned for all.

These requirements are a willful violation of the JavaScript specification current at the time of writing (ECMAScript edition 5). The JavaScript specification requires that the ToBoolean() operator convert all objects to the true value, and does not have provisions for objects acting as if they were undefined for the purposes of certain operators. This violation is motivated by a desire for compatibility with two classes of legacy content: one that uses the presence of document.all as a way to detect legacy user agents, and one that only supports those legacy user agents and uses the document.all object without testing for its presence first.

因此,document.all 是此 ECMAScript 规则的唯一官方异常(exception)。 (在 Opera 中,document.attachEvent 等也是假的,但在任何地方都没有指定。)

关于javascript - 根据规范,JavaScript 中的所有对象都是真实的,但在 DOM 中,一个非原始对象不是。哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10348995/

相关文章:

javascript - 单击时 ionic 显示全屏图像

javascript - 如何使用feathers.js避免服务在钩子(Hook)中多次运行?

c++ - 为什么我不能将方法链接到构造函数?

javascript - 更改当前选项卡或浏览器窗口的标题

Perl 对象错误 : Can't locate object method via package

javascript将数组转换为对象以通过ajax发送数据

javascript - 在 Angular 中使用 ngrx 时捕获超时错误

javascript - 我无法使用javascript从android ajax获取responseText的数据

javascript - 复制 <li> 并将它们插入到它们之后

javascript - 如何克隆元素及其关联的事件回调?