gpt4 book ai didi

javascript - 为什么 document.all 是假的?

转载 作者:IT王子 更新时间:2023-10-29 03:13:04 26 4
gpt4 key购买 nike

document.all 是 DOM 中的非原始对象,它是 falsy。

例如,这段代码什么都不做:

if (document.all) {
alert("hello");
}

谁能解释这是为什么?

最佳答案

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


我问的问题如下。

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 等也是假的,但在任何地方都没有指定。)

上面的文字解释了为什么这样做。但这里有一个在旧网页上很常见的示例代码片段,它将进一步说明这一点:

if (document.all) {
// code that uses `document.all`, for ancient browsers
} else if (document.getElementById) {
// code that uses `document.getElementById`, for “modern” browsers
}

基本上,很长一段时间以来,document.all都是通过这种方式来检测旧浏览器的。因为 document.all 首先经过测试,所以提供这两种属性的更多现代浏览器仍将在 document.all 代码路径中结束。在现代浏览器中,我们更愿意使用 document.getElementById,当然,但是由于大多数浏览器仍然有 document.all(出于其他向后兼容性的原因)else 如果 document.all 为真,则永远不会被访问。如果代码以不同的方式编写,这将不是问题:

if (document.getElementById) {
// code that uses `document.getElementById`, for “modern” browsers
} else if (document.all) {
// code that uses `document.all`, for ancient browsers
}

但遗憾的是,许多现有代码以相反的方式进行。

解决此问题的最简单方法是简单地使 document.all 在仍然模仿它的浏览器中为 falsy。

关于javascript - 为什么 document.all 是假的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10350142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com