本文介绍了在Express和Node.js中,是否可以扩展或覆盖响应对象的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于每个中间件,Express都会传递 res req 对象。这些对象分别扩展来自 http.ServerResponse http.ClientRequest 的原生对象。我想知道是否可以覆盖或扩展响应对象的方法。

With every middleware, Express passes a res and a req objects. These objects extend the native ones that come from http.ServerResponse and http.ClientRequest respectively. I'd like to know if it's possible to override or extend methods of the response object.

例如,而不是 res.render(' home',jsonData); ,我想用一个名为customRender的自定义方法扩展 res 并像这样使用它: res.customRender()

For example, instead of res.render('home', jsonData);, I'd like to extend res with a custom method called customRender and use it like so: res.customRender().

我没有遇到特定问题或任何问题。我只想学习如何扩展本机对象,或者就像这种情况一样,来自Node.js中的第三方模块的对象

I'm not stuck at a particular problem or anything. I'd just like to learn how to extend native objects or, as with this case, object that come from 3rd party modules in Node.js

推荐答案

最好的想法是将自定义方法添加到响应对象的原型中:

The best idea would be to add a custom method to the prototype of the response object:

var express = require("express");

express.response.customRender = function() {
    // your stuff goes here
};

此功能应该可以通过每个 res object。

And this function should be accessible by every res object.

您可以阅读源代码以了解它们如何扩展本机对象。基本上他们正在进行原型链接:

You can read the source code to see how they extend native objects. Basically they are doing prototype chaining:

express / lib / response.js

var res = module.exports = {
  __proto__: http.ServerResponse.prototype
};

此对象成为newely创建的响应对象(来自连接框架)的原型:

And this object becomes a prototype of newely created response object (which comes from connect framework):

res.__proto__ = app.response;

app.response 只是别名到上面定义的 res 。请注意, __ proto __ 属性是对对象原型的引用。

(app.response is just an alias to res defined above). Note that __proto__ property is a reference to the prototype of an object.

但请注意。首先, __ proto __ 不是EcmaScript的一部分(它可能在其他JavaScript实现中不可用)。其次:通常你会用 Object.create 进行继承(直接在一个对象上设置 __ proto __ 是猴子修补它通常是一种不好的做法,它可能会破坏很多东西)。在这里阅读更多相关信息:

Be warned though. First of all __proto__ is not a part of EcmaScript (it might not be available in other JavaScript implementations). Secondly: normally you would do inheritance with Object.create (setting __proto__ directly on an object is a monkey patching and it is generally a bad practice, it may break many things). Read more about that here:

这篇关于在Express和Node.js中,是否可以扩展或覆盖响应对象的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 13:23