Different ways to extend classes in node.js

Extending prototype classes in node.js or javascript in general. (js newb)

I looked at the source code of expressjs and saw this :

var mixin = require('utils-merge'); 
....
mixin(app, proto);
mixin(app, EventEmitter.prototype);

Utils-mergeLooks like an external module. What is the difference above and just something like:

var util = require('util');
....
util.inherit(app, proto);
util.inherit(app, EventEmitter);

And still trying to expand properties? I am kind, lost here:

app.request = { __proto__: req, app: app }; // what is the equivalent for this in util?
app.response = { __proto__: res, app: app };

If so, will it work, even if used util.inherit?

app.request = util.inherit(app, req)

Or something like that? jshint says it's __proto__stripped.


Also, have I also seen this?

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

Could it be?

var res = module.exports = util.inherits...??
+4
source share
2 answers

I watched the source code expressjs

, app .

utils-merge , - :

var util = require('util');
....
util.inherit(app, proto);
util.inherit(app, EventEmitter);

:

utils-merge
.

util.inherits

. , superConstructor.

!

app ( ) , , () - , createApplication. , " ". utils.inherits , .prototype.

mixin proto, EventEmitter.prototype app.

? , :

app.request = { __proto__: req, app: app }; // what is the equivalent for this in util?
app.response = { __proto__: res, app: app };

Object.create:

app.request = Object.create(req);
app.request.app = app;
app.response = Object.create(res);
app.response.app = app;

, , util.inherit?

app.request = util.inherit(app, req) // Or something like that?

, .

jshint , __proto__ .

, Object.create. __proto__, , .

, ?

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

?

var res = module.exports = util.inherits...??

, -, Object.create:

var res = module.exports = Object.create(http.ServerResponse.prototype);
+6

ES6 Node.js.

class myClass() {
  this.hi = function(){"hello"};

}

class myChild extends myClass() {

}

var c = new myChild(); c.hi(); //hello
+2

All Articles