【发布时间】:2017-09-28 13:53:57
【问题描述】:
作为我学习 Node 内部结构的一部分,我正在尝试向 Node 响应原型添加一些基本功能,而不需要一些外部库。这应该不是一项艰巨的任务,但是,响应永远不会传递给新函数,也永远无法通过 this 语句检索。这是一个将模板渲染函数绑定到服务器响应的示例。
const http = require('http');
const newMethods = Object.create(http.ServerResponse.prototype);
newMethods.render = async (view, data) => {
const renderResult = await aTemplateLibray(view, data);
this.writeHead(200, {'Content-Type': 'text/html'});
this.end(renderResult);
}
// Other methods here...
// Then
Object.assign(http.ServerResponse.prototype, newMethods);
module.exports = http;
一旦我使用了这个http服务器,我就可以使用新的渲染函数,但是响应没有传递给它,所以会抛出一个错误信息,比如this.writeHead is not a function .
我也尝试过 Object.defineProperty 方法。
Object.defineProperty(http.ServerResponse.prototype, 'render',
{writable: true,
enumerable: true,
get: return this.socket.parser.incoming
});
我找到了一些旧库,它使用旧的 __defineGetter__ 方法返回了那个套接字,我用新的形式对其进行了测试,但它也不起作用。
【问题讨论】:
-
第一个版本没有多大意义(创建对象,添加属性,然后复制该属性到原型没有意义),此外使用箭头函数,所以
this当然不是你所期望的(更多在this question,虽然在某处有更好的)。defineProperty版本甚至不会解析。
标签: javascript node.js http prototype middleware