在node.js中扩展类的不同方式
一般在node.js或javascript中扩展原型类。 (js newb)
我在看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__
被depricated。
另外我也看到了这个?
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.inherits
将原型方法从一个构造函数inheritance到另一个构造函数。 构造函数的原型将被设置为由superConstructor创build的新对象。
另外阅读他们的 来源 !
app
(虽然是一个奇怪的原因函数)不是一个构造函数,但应该是一个(普通)对象 – 一个由createApplication
的实例 。 所以在这里没有办法做“类inheritance”。 不pipe怎样,你不能在同一个构造函数中多次使用utils.inherits
,因为它覆盖了它的.prototype
属性。
相反,该mixin
函数将简单地复制proto
所有属性,然后从EventEmitter.prototype
所有属性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
函数来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__
被depricated。
是的,你应该使用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