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

The JavaScript class syntax added in ES6 seems to make it legal for extend null :

 class foo extends null {} 

Some Googling reveals that he suggested on ES Discuss that such announcements should be made a mistake; however, other commentators claimed that they were left legitimate on the grounds that

someone might want to create a class with the prototype {__proto__: null}

and this side of the argument ultimately prevailed.

I cannot fully understand this hypothetical use case. First, although declaring such a class is legal, it seems that creating an instance of a class declared in this way is not. Trying to instantiate foo class on top in Node.js or Chrome gives me a wonderful error

 TypeError: function is not a function 

doing the same in firefox gives me

 TypeError: function () { } is not a constructor 

This does not help to define the class constructor, as shown in the current MDN function example; if I try to instantiate this class:

 class bar extends null { constructor(){} } 

then Chrome / Node tell me:

 ReferenceError: this is not defined 

and Firefox tells me:

 ReferenceError: |this| used uninitialized in bar class constructor 

What is this madness? Why are these nullable classes incompatible? And considering that they are not real, why did the opportunity to create them appear deliberately gone into the specification, and why did some MDN author think it was remarkable enough for documentation ? What is the possible use case for this function?

+57
javascript ecmascript-6 es6-class
Dec 16 '16 at 17:06
source share
2 answers

Creating instances of such classes is designed to work; Chrome and Firefox have errors. Here is Chrome, here is Firefox. It works great in Safari (at least on the host).

There was a mistake in the specification earlier that made them impossible to create, but it was fixed for a while. (There is still connected, but that is not what you see.)

The usage example is about the same as that of Object.create(null) . Sometimes you need something that is not inherited from Object.prototype .

+23
Dec 17 '16 at 22:05
source share

To answer the second part:

I cannot fully understand this hypothetical use case.

This way your object will not have Object.prototype in the 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 you know, undefined actually not a function. In this case, we can create objects without fear of calling in a field that should not be there.

This is a generic pattern via Object.create(null) and is common in many basic codes, including large ones such as NodeJS.

+10
Dec 20 '16 at 21:40
source share



All Articles