在node.js中扩展类的不同方法

Different ways of extending classes in node.js

本文关键字:方法 扩展 node js      更新时间:2023-09-26

在node.js或javascript中扩展原型类。(js新手(

我在看expressjs的源代码时看到了这个:

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

Utils-merge看起来像是一个外部模块。以上和仅仅做一些类似的事情有什么区别:

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

这是否仍在试图扩展属性?我很善良——迷失在这里:

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

如果是的话,即使使用了util.inherit,它还会起作用吗?

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

或者类似的东西?jshint说__proto__是去复杂化的。


另外我也看到了这个?

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

这可能是吗?

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

我在看expressjs 的源代码

您可能还想看看这个关于app应该如何工作的问题。

utils-merge之间有什么区别如上所述,只是做一些类似的事情:

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

他们在做完全不同的事情:

utils合并
将源对象的属性合并到目标对象中

util.继承

将原型方法从一个构造函数继承到另一个构造函数。构造函数的原型将被设置为从创建的新对象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);

您可以在Node.js.中使用ES6

class myClass() {
  this.hi = function(){"hello"};
}
class myChild extends myClass() {
}
var c = new myChild(); c.hi(); //hello