使用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.authenticateRememberMeStragety.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。