How and why would I write a class that extends null?

老子叫甜甜 提交于 2019-12-02 19:55:53

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).

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.)

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

Benjamin Gruenbaum

To answer the second part:

I can't make much sense of this hypothetical use case.

That way, your object won't have Object.prototype in its prototype chain.

class Hash extends null {}
var o = {};
var hash = new Hash;
o["foo"] = 5;
hash["foo"] = 5;
// both are used as hash maps (or use `Map`).
hash["toString"]; // undefined
o["toString"]; // function

As we know, undefined in fact is not a function. In this case we can create objects without fearing a call on a field that shouldn't be there.

This is a common pattern through Object.create(null) and is common in a lot of code bases including big ones like NodeJS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!