Can I use http.ServerResponse as a prototype in node.js?

I can't get this to work:

var proxyResponse = function(res) {
  return Object.create(res);
};

Calling standard response methods on the object returned by this method does not work, for example:

http.createServer(function(req, res) {
  res = proxyResponse(res);
  res.writeHead(200, {"Content-Type": "text/html"});

  res.end("Hallelujah! (Praise the Lord)");
}).listen(8080);

The server just freezes. Can someone explain what I'm doing wrong?

+1
source share
1 answer

From MDC :

Object.create(proto [, propertiesObject ])

This will create a new object, the prototype of which is proto, the object itself does not determine:

res.foo = function() {
    console.log(this);
}
res.foo();
res = proxyResponse(res);
res.foo();

Result:

{ socket: 
   { fd: 7,
     type: 'tcp4',
     allowHalfOpen: true,
     _readWatcher: 
      { socket: [Circular],
....

{}

So why doesn't he throw a mistake and explode? Besides the distorted search and setting of properties, there is one reason why it does not work.

As long as your new object refers to the same object as the old one, it is NOT old.

: https://github.com/ry/node/blob/a0159b4b295f69e5653ef96d88de579746dcfdc8/lib/http.js#L589

if (this.output.length === 0 && this.connection._outgoing[0] === this) {

, this - , this.connection._outgoing[0] - , .

, , Object.create, , res , res , .

+4

All Articles