换句话说,为什么DOMException不像AggregateError,EvalError等?

devtools evaluation screenshot Both expressions evaluate to true:

Object.getPrototypeOf(DOMException) === Function.prototype
Object.getPrototypeOf(DOMException.prototype) === Error.prototype

我过go 常常认为下面的概括没有反例:

如果

  • X和Y是构造函数,并且
  • Y不是Object()构造函数,并且
  • X.Prototype将Y.Prototype作为其[[Prototype]]对象 然后
  • X将Y作为其[[Prototype]]对象

例如,上述概括适用于下面的X、Y对

  1. HTMLElement,元素
  2. AggregateError,错误
  3. AsyncFunction,函数
  4. node ,事件目标
  5. 元素、 node
  6. RTCError,DOMException

据我所知,泛化失败的唯一情况是当X=DOMException和Y=Error时.

为什么DOMException构造函数本身不能将Error构造函数作为其[[Prototype]],还有更深层次的原因吗?

推荐答案

If X.prototype has Y.prototype as its [[Prototype]] object,
Then X has Y as its [[Prototype]] object

不,这不是一个有效的概括.这很常见,但并不是无处不在.这种模式是在ES6classes通过原型链引入static个属性(特别是方法)的继承之后才开始出现的.在此之前,构造函数都是从Function.prototype继承而来的纯函数.许多图书馆仍在这样做.

然而,这种普遍性适用于几乎所有的内置类,包括本机类(由ECMAScript定义)和主机提供的类(如DOM).对于the Error hierarchy,这是有意识地在ES6中引入的,在ES5.1中,the native error constructors仍然继承自Function.prototype.

对于Web API,其接口的Web IDL规范prescribes just this pattern:

  1. Let 100 be 101.[[Intrinsics]].[[%Function.prototype%]].
  2. 一百零五

  1. […]if 102 is declared to inherit from another interface, then set 103 to the 100 in realm of that 101..
  2. […]
  3. 一百零二

看看这些规则,实际上还有第二个例外:Window构造函数继承自EventTarget,但Window.prototype继承自WindowProperties对象(后者又继承EventTarget.prototype).

为什么DOMException构造函数本身不能将Error构造函数作为其[[Prototype]],还有更深层次的原因吗?

不是的.不过,有几个可能的解释:

  • 它太老了,DOMException已经是第一个浏览器js实现的一部分了
  • 没人更新
  • 它与网络不兼容,无法进行更新
  • 这只是一个疏忽
  • 它已经更新了,但浏览器还没有实现它

Edit: Actually Web IDL explicitly describes it as an exception to the rule. It does not inherit from Error, but it still "has its [[Prototype]] internal slot set to the intrinsic object %Error.prototype%". This was discussed in issue #55changed in PR #378 to align with the implementation reality - away from the previously described [[Prototype]] value of %Error%.

Javascript相关问答推荐

为什么我达到了时间限制!?LeetCode链接列表循环(已解决,但需要解释!)

在JavaScript中对大型级联数组进行切片的最有效方法?

为什么getRecord()会因为与_logger相关的错误而失败?(使用Hedera SDK)

Redux工具包查询(RTKQ)端点无效并重新验证多次触发

硬币兑换运行超时

Angular中计算信号和getter的区别

Angular 17—每当一个布尔变量变为真时触发循环轮询,只要它保持为真

当运行d3示例代码时,没有显示任何内容

Chromium会将URL与JS一起传递到V8吗?

JS,当你点击卡片下方的绿色空间,而它是在它的背后转动时,

Javascript json定制

使用Promise.All并发解决时,每个promise 的线性时间增加?

类构造函数不能在没有用With Router包装的情况下调用

未加载css colored颜色 ,无法将div设置为可见和不可见

JS Animate()方法未按预期工作

删除元素属性或样式属性的首选方法

P5play SecurityError:无法从';窗口';读取命名属性';Add';:阻止具有源的帧访问跨源帧

我们是否可以在reactjs中创建多个同名的路由

Firefox的绝对定位没有达到预期效果

如果查询为空,则MongoDB将所有文档与$in匹配