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

maj*_*rif 4 javascript node.js

一般来说,扩展node.js或javascript中的原型类.(js newb)

我正在查看expressjs的源代码并看到了这个:

var mixin = require('utils-merge'); 
....
mixin(app, proto);
mixin(app, EventEmitter.prototype);
Run Code Online (Sandbox Code Playgroud)

Utils-merge看起来像是一个外部模块.上面有什么区别,只做以下事情:

var util = require('util');
....
util.inherit(app, proto);
util.inherit(app, EventEmitter);
Run Code Online (Sandbox Code Playgroud)

这仍然是在尝试扩展属性吗?我很善良 - 迷失在这里:

app.request = { __proto__: req, app: app }; // what is the equivalent for this in util?
app.response = { __proto__: res, app: app };
Run Code Online (Sandbox Code Playgroud)

如果是这样,即使util.inherit使用它仍然有效吗?

app.request = util.inherit(app, req)
Run Code Online (Sandbox Code Playgroud)

或类似的东西?jshint说__proto__是被剥夺了.


另外我也看到了这个?

var res = module.exports = {
  __proto__: http.ServerResponse.prototype
};
Run Code Online (Sandbox Code Playgroud)

这可能吗?

var res = module.exports = util.inherits...??
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 6

我正在查看expressjs的源代码

你可能也想看看这个问题如何app应该工作.

上面有什么区别utils-merge ,只是做了类似的事情:

var util = require('util');
....
util.inherit(app, proto);
util.inherit(app, EventEmitter);
Run Code Online (Sandbox Code Playgroud)

他们做的事情完全不同:

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

util.inherits

将原型方法从一个构造函数继承到另一个构造函数.构造函数的原型将设置为从superConstructor创建的新对象.

也看过他们的 来源!

app(虽然是一个奇怪的原因的函数)不是一个构造函数,但应该是一个(普通)对象 - 由一个实例createApplication.所以这里没有办法做"类继承".并且你不能utils.inherits在同一个构造函数上多次使用,因为它会覆盖它的.prototype属性.

相反,该mixin函数将简单地复制所有属性proto,然后将所有属性复制EventEmitter.prototypeapp对象.

这仍然是在尝试扩展属性吗?我很善良 - 迷失在这里:

app.request = { __proto__: req, app: app }; // what is the equivalent for this in util?
app.response = { __proto__: res, app: app };
Run Code Online (Sandbox Code Playgroud)

使用本机Object.create函数:

app.request = Object.create(req);
app.request.app = app;
app.response = Object.create(res);
app.response.app = app;
Run Code Online (Sandbox Code Playgroud)

如果是这样,即使util.inherit使用它仍然有效吗?

app.request = util.inherit(app, req) // Or something like that?
Run Code Online (Sandbox Code Playgroud)

不,真的不是.

jshint说__proto__是被剥夺了.

是的,你应该使用Object.create.但非标准__proto__可能会保留兼容性.

另外我也看到了这个?

var res = module.exports = {
  __proto__: http.ServerResponse.prototype
};
Run Code Online (Sandbox Code Playgroud)

这可能吗?

var res = module.exports = util.inherits...??
Run Code Online (Sandbox Code Playgroud)

不,这是一个案例Object.create:

var res = module.exports = Object.create(http.ServerResponse.prototype);
Run Code Online (Sandbox Code Playgroud)