通常在 node.js 或 javascript 中扩展原型(prototype)类。 (js 新手)
我正在查看 expressjs 的源代码并看到 this :
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...??
最佳答案
您可能还想查看 this question 以了解 app
应该如何工作。
他们在做完全不同的事情:
另请阅读 their sources !app
(虽然由于奇怪的原因是一个函数)不是一个构造函数,而是应该是一个(普通)对象 - createApplication
制作的 实例 。所以这里没有办法做“类继承”。而且你不能在同一个构造函数上多次使用 utils.inherits
,因为它会覆盖它的 .prototype
属性。
相反,该 mixin
函数将简单地从 proto
复制所有属性,然后从 EventEmitter.prototype
复制所有属性到 app
对象。
为此使用 native Object.create
函数:
app.request = Object.create(req);
app.request.app = app;
app.response = Object.create(res);
app.response.app = app;
不,真的不是。
是的,您应该改用
Object.create
。但是为了兼容性可能会保留 nonstandard __proto__
。不,这又是
Object.create
的情况:var res = module.exports = Object.create(http.ServerResponse.prototype);
关于javascript - 在 node.js 中扩展类的不同方式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24809786/