Confusion about setting something.prototype.__proto__

后端 未结 2 1686
梦毁少年i
梦毁少年i 2020-12-08 23:21

In the code for the Express module for Node.js I came across this line, setting inheritance for the server:

Server.prototype.__proto__ = connect.HTTPServer.p         


        
2条回答
  •  醉酒成梦
    2020-12-09 00:08

    The non-standard property __proto__ lets you set the prototype of an existing object.

    In your example, both version will achieve the same effect, but there is a difference:

    child1's prototype is the same as parent's prototype, whereas child2's prototype is an empty object and this empty object's prototype is the same as parent's prototype.

    Of course as child2 and its prototype don't have a method test, this method will be looked up further up in the prototype chain.

    Also consider this:

    You want to create only one object that should inherit from another object. Now, you could write a constructor function, but JavaScript has object literal notation to create objects directly and you want to use it.

    If you have a constructor function, letting the new objects inherit from another object is as easy a setting the prototype of the constructor function to that object.

    Obviously this does not work for object literals. But in Firefox you can use __proto__ to set it:

    var server = {
        __proto__: connect.HTTPServer.prototype,
        other: properties
    };
    

    As this property is not standard, you should avoid using it.

提交回复
热议问题