javascript 在 Express 和 Node.js 中,是否可以扩展或覆盖响应对象的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18304436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:23:42  来源:igfitidea点击:

In Express and Node.js, is it possible to extend or override methods of the response object?

javascriptnode.jsoopexpress

提问by M.K. Safi

With every middleware, Express passes a resand a reqobjects. These objects extend the native ones that come from http.ServerResponseand http.ClientRequestrespectively. I'd like to know if it's possible to override or extend methods of the response object.

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

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

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

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

我不会被某个特定的问题或任何事情困住。我只想学习如何扩展本机对象,或者在这种情况下,来自 Node.js 中的 3rd 方模块的对象

回答by freakish

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
};

And this function should be accessible by every resobject.

并且这个函数应该可以被每个res对象访问。

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

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

express/lib/response.js

快递/lib/response.js

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

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

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

res.__proto__ = app.response;

(app.responseis just an alias to resdefined above). Note that __proto__property is a reference to the prototype of an object.

app.response只是res上面定义的别名)。请注意,__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:

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain

回答by elijahoyekunle

As freakish answered, you can add a method to the prototype. However, it won't have access to other members of the created object. If you want to have that access, you need to go a step further. This is a full example:

正如freakish 回答的那样,您可以向原型添加一个方法。但是,它无法访问所创建对象的其他成员。如果您想获得该访问权限,则需要更进一步。这是一个完整的例子:

const express = require('express');

const myExpress = Object.create(express().response, {
  data: {
    value: function(data) {
      return this.status(200).json({status: true, data: data});
    },
  },
  message: {
    value: function(msg) {
      return this.status(200).json({status: true, message: msg});
    },
  },
});

This way, you can create your express objects like this:

这样,你可以像这样创建你的 express 对象:

const app = express();
app.response = Object.create(myExpress);

From the response objects, you'll be able to call the messageand datafunctions directly.

从响应对象中,您将能够直接调用messagedata函数。