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

后端 未结 2 1378
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 05:20

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

class foo extends null {}

Some Googling reveals that it was

2条回答
  •  孤街浪徒
    2021-02-02 05:42

    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.

提交回复
热议问题