我如何以及为什么要编写一个扩展null的类? [英] How and why would I write a class that extends null?

查看:94
本文介绍了我如何以及为什么要编写一个扩展null的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ES6中添加的JavaScript的类语法显然使其合法 extend null

JavaScript's class syntax, added in ES6, apparently makes it legal to extend null:

class foo extends null {}

一些谷歌搜索显示在ES讨论中建议这样的声明一个错误;然而,其他评论者认为他们是合法的

Some Googling reveals that it was suggested on ES Discuss that such declarations be made an error; however, other commenters argued for them to be left legal on the basis that


有人可能想要创建一个<$ c的类$ c> {__ proto__:null} prototype

someone might want to create a class that has a {__proto__: null} prototype

并且论证的那一方最终占了上风。

and that side of the argument ultimately prevailed.

我无法理解这个假设的用例。首先,虽然这样一个类的声明是合法的,但似乎实例化以这种方式声明的类不是。试图在Node.js或Chrome中从上面实例化类 foo 给我一个奇妙的愚蠢错误

I can't make much sense of this hypothetical use case. For one thing, while the declaration of such a class is legal, it seems that instantiating a class declared in this way isn't. Trying to instantiate the class foo from above in Node.js or Chrome gives me the wonderfully daft error

TypeError: function is not a function

在Firefox中执行相同操作时我

while doing the same in Firefox gives me

TypeError: function () {
} is not a constructor

在类中定义构造函数没有帮助,如MDN当前的特性示例所示;如果我尝试实例化这个类:

It doesn't help to define a constructor on the class, as shown in MDN's current example of the feature; if I try to instantiate this class:

class bar extends null {
  constructor(){}
}

然后Chrome / Node告诉我:

then Chrome/Node tell me:

ReferenceError: this is not defined

并且Firefox告诉我:

and Firefox tells me:

ReferenceError: |this| used uninitialized in bar class constructor

这些疯狂是什么?为什么这些空扩展类不可实例化?鉴于它们不是可实例化的,为什么有意创建它们的可能性留在规范中,为什么一些MDN作者认为它是值得注意的是文档?这个功能有什么可能的用例?

What is all this madness? Why are these null-extending classes not instantiable? And given that they're not instantiable, why was the possibility of creating them deliberately left in the spec, and why did some MDN author think that it was noteworthy enough to document? What possible use case is there for this feature?

推荐答案

实例化这些类是有用的; Chrome和Firefox只是有bug。 这里是 Chrome,这里是 Firefox的。它在Safari中工作正常(至少在master上)。

Instantiating such classes is meant to work; Chrome and Firefox just have bugs. Here's Chrome's, here's Firefox's. It works fine in Safari (at least on master).

曾经有一个 bug 使它们无法实例化,但它已经修复了一段时间。 (仍然是一个相关的,但这不是你所看到的。)

There used to be a bug in the spec which made them impossible to instantiate, but it's been fixed for a while. (There's still a related one, but that's not what you're seeing.)

用例与 Object.create(null)的用例大致相同。有时你想要一些不从 Object.prototype 继承的东西。

The use case is roughly the same as that of Object.create(null). Sometimes you want something which doesn't inherit from Object.prototype.

这篇关于我如何以及为什么要编写一个扩展null的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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