我是否遗漏了什么,或者是否无法像 Java 类那样扩展任意 Node 模块?
具体示例:
我需要 passport-remember-me
将 req
对象公开给 _issue
方法。我试图做的是扩展该函数(RememberMe.Strategy
),修改_issue
函数,然后委托(delegate)给原始父类的函数来处理实际的业务逻辑:
// 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);
};
最佳答案
进行面向对象时不要使用箭头函数。这是因为箭头函数是故意设计来破坏 this
的工作方式的。相反,请执行以下操作:
IWillRememberYou.prototype.authenticate = function (req, options) {
/* .. */
};
请记住,使用箭头函数,您基本上将 this
绑定(bind)到定义该函数的上下文。如果您在任何函数之外定义它,则 this
将是全局对象,或者在严格模式下为 undefined
。
这归结为箭头函数破坏了继承。
关于node.js - 使用 OOP 扩展 Node.js 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38649559/