使用OOP扩展Node.js模块
我是否错过了某些东西,还是仅仅是不可能扩展像Java类那样的任意Node模块?
具体例子:
我需要passport-remember-me
来将req
对象暴露给_issue
方法。 我试图做的是扩展该function( RememberMe.Strategy
),修改_issue
函数,然后委托给原始父类的函数为实际的业务逻辑:
// 1: Extend RememberMeStrategy function IWillRememberYou (options, verify, issue) { RememberMeStrategy.call(this, options, verify, issue); } util.inherits(RememberMeStrategy, IWillRememberYou); // 2: Override some method IWillRememberYou.prototype.authenticate = (req, options) => { // Save original function const issue = this._issue; // Wrap the supplied callback so it can now be sent extra args this._issue = (user, issued) => { // Send in additional parameter issue(req, user, issued); }; };
这个给我的是在IWillRememberYou.authenticate
和RememberMeStragety.authenticate
里面的this
上下文。 为什么会这样?
父类看起来像什么(第三方Node模块)
function Strategy(options, verify, issue) { // ... passport.Strategy.call(this); // ... this._issue = issue; } util.inherits(Strategy, passport.Strategy); Strategy.prototype.authenticate = function(req, options) { // ... // My end goal is to send (req, user, issued) to that callback this._issue(user, issued); };
做OO时不要使用箭头function。 这是因为箭头function是故意devise来打破this
工作。 相反:
IWillRememberYou.prototype.authenticate = function (req, options) { /* .. */ };
请记住,使用箭头函数,您基本上将其绑定到定义函数的上下文中。 如果你在任何函数之外定义它,那么this
将是全局对象,或者在严格模式下是undefined
。
这可以归结为箭头函数打破inheritance。
- Javascriptinheritance对象覆盖其他inheritance对象
- 我可以在ES6的父类的静态方法中使用类variables吗?
- Nodejs + expressjs中的类成员inheritance
- 复杂的循环Node模块依赖抛出“TypeError:”inheritance“的超级构造函数必须有一个原型”
- 在Express上使用外部模块进行Jade模板inheritance的一个很好的策略
- 无法看到从子对象添加到原型的属性
- 如何在NodeJS中为自定义错误类获取正确的回溯?
- Mongoose模式inheritance和模型填充
- 使用Node.js,Handlebars和Express进行模板inheritance