gpt4 book ai didi

javascript - JavaScript 中的 XMLHttpRequest 是什么类型?

转载 作者:数据小太阳 更新时间:2023-10-29 04:45:56 25 4
gpt4 key购买 nike

我想知道 XMLHttpRequest 对象在 JavaScript 中的标准类型是什么。我发现不同的引擎会产生不同的结果。

在 Firefox 和 Chrome 中:

typeof XMLHttpRequest //=> "function"

在 Safari 中:

typeof XMLHttpRequest //=> "object"

W3C规范使用interface关键字来定义XMLHttpRequestwhich is not used in practice :

[Constructor(optional XMLHttpRequestOptions options)]
interface XMLHttpRequest : XMLHttpRequestEventTarget {
// ...
}

MDN definition指出:

XMLHttpRequest is a JavaScript object...

但是 Firefox 返回 “function”,所以这个术语至少是模糊的。该定义目前还规定:

It's now being standardized in the W3C.

我到处看了看,但没有明确的答案™。有吗?

除此之外,还有一些额外的背景


问题背景

我刚刚修复了这段代码中的错误:

if (typeof XMLHttpRequest === "function") {
// do something
}

该bug目前只出现在Safari 7中(其他版本未测试)。该代码在 Firefox 和 Chrome 中运行良好。修复是:

if (typeof XMLHttpRequest !== "undefined") {
// do something
}

问题来自假设 typeof XMLHttpRequest 在任何地方都是相同的...

最佳答案

根据 ECMAScript 5 和 Web IDL 规范,Safari 在这里似乎是错误的。 typeof XMLHttpRequest 应该返回 "function"

WebIDL spec says :

If the interface is declared with a [Constructor] extended attribute, then the interface object can be called as a function to create an object that implements that interface.

...

The internal [[Call]] method of the interface object behaves as follows...

与此同时,specification for typeof in the ESCAScript 5 spec有一个包含条目的返回值表:

Object (native or host and does implement [[Call]]) : "function"

Object (host and does not implement [[Call]]) : Implementation-defined except may not be "undefined", "boolean", "number", or "string".

从这个表中,我们可以看到任何实现[[Call]] 的对象—— native 或主机——都需要导致typeof 产生“功能”。 WebIDL 规范要求 [Constructor] 接口(interface)对象来实现 [[Call]],因此它们应该产生 “function”

关于javascript - JavaScript 中的 XMLHttpRequest 是什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30721648/

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