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


with every middleware, express passes res , req objects. these objects extend native ones come http.serverresponse , http.clientrequest respectively. i'd know if it's possible override or extend methods of response object.

for example, instead of res.render('home', jsondata);, i'd extend res custom method called customrender , use so: res.customrender().

i'm not stuck @ particular problem or anything. i'd learn how extend native objects or, case, object come 3rd party modules in node.js

the best idea add custom method prototype of response object:

var express = require("express");  express.response.customrender = function() {     // stuff goes here }; 

and function should accessible every res object.

you can read source code see how extend native objects. doing prototype chaining:

express/lib/response.js

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

and object becomes prototype of newely created response object (which comes connect framework):

res.__proto__ = app.response; 

(app.response alias res defined above). note __proto__ property reference prototype of object.

be warned though. first of __proto__ not part of ecmascript (it might not available in other javascript implementations). secondly: inheritance object.create (setting __proto__ directly on object monkey patching , bad practice, may break many things). read more here:

https://developer.mozilla.org/en-us/docs/web/javascript/guide/inheritance_and_the_prototype_chain


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo