Have a look at the diagram on this page (mckoss.com) that shows the prototype
, constructor
, __proto__
relations for a small hierarchy. Also the code below the diagram describes the relation quite well.
When you have a function Base
, and set the prototype of the function object defined, the statement Derived.prototype = new Base;
sets the __proto__
(actually the internal [[prototype]]
) of Derived.prototype
to Base.prototype
automatically, making Derived itself a class that you can instantiate objects from. This seems the be a more standards compliant way of defining a derived class.
From what I read, __proto__
is a non-standard way of accessing the internal [[prototype]]
of an object. It seems to be well supported, but I am not sure if it should be trusted.
In any case, your example Server.prototype.__proto__ = connect.HTTPServer.prototype;
seems to do the derivation the other way around: first define an object, Server
by defining the constructor and the proto, and then hook up the internal [[prototype]]
manually to morph it into a class derived from HTTPServer
.
As for your suggested alternative, Server.prototype = connect.HTTPServer.prototype;
: that is a bad idea. Here, you are setting the prototype of Server
to be the same object as the prototype of HTTPServer
. So any changes you make to Server
class will be directly reflected in HTTPServer
, and will be accessible from other derived classes of HTTPServer
. You can imageine the chaos if two classes derived from HTTPServer
try to define the same member.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…