Why *not* “inherit”/extend from Object in JavaScript?

后端 未结 1 1656
臣服心动
臣服心动 2021-02-05 19:32

It is well-known that declaring objects with JSON notation makes them \"inherit\" from (or, more precisely, to be built like) the base Object:

myobj={a:1, b:2};

相关标签:
1条回答
  • 2021-02-05 19:51

    Instead of this:

    myobj = Object.create(Object);
    

    ...I think you mean this is the equivalent:

    myobj = Object.create(Object.prototype);
    

    ...because:

    Object.getPrototypeOf( {a:1, b:2} ) === Object.prototype;  // true
    

    As to why to use null early, if your object has no need for any of the properties of Object.prototype, ending the chain early would technically (though marginally) speed up property lookups when a property does not exist on the object in question.

    Note that I say "early" because the chain always ends with null.

    Object.getPrototypeOf( Object.prototype );  // null
    

    
                 obj ----------> proto -------> Object.proto -----> null
             +---------+      +---------+      +-------------+     
             |         |      |         |      |             |
             |  foo:1  |      |  bar:1  |      | toString:fn |      null
             |         |      |         |      |             |
             +---------+      +---------+      +-------------+ 
                  ^                ^                  ^               X
                  |                |                  |               |
    obj.foo ------+                |                  |               |
                  ^                |                  |               |
    obj.bar-------+----------------+                  |               |
                  ^                ^                  |               |
    obj.toString--+----------------+------------------+               |
                  ^                ^                  ^               |
    obj.baz-------+----------------+------------------+---------------+
    
       ^---property lookups
    

    Notice that the baz property does not exist anywhere in the prototype chain.

    Because of this, it needs to search each object in sequence until it finally reaches null before it realizes that baz doesn't exist anywhere.

    If you eliminate the Object.prototype from the chain, it will get to null a little quicker.

    0 讨论(0)
提交回复
热议问题