使用 OOP 扩展 Node.js 个模块
Extending Node.js Modules with OOP
我是不是遗漏了什么,或者只是无法像 Java class 那样扩展任意 Node 模块?
具体例子:
我需要 passport-remember-me
将 req
对象暴露给 _issue
方法。我试图做的是扩展该功能 (RememberMe.Strategy
),修改 _issue
功能,然后将实际业务逻辑委托给原始父 class' 功能:
// 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
上下文。为什么会这样??
父class长什么样(第三方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
绑定到定义函数的上下文。如果你在任何函数之外定义它,那么 this
将是全局对象,或者如果在严格模式下 undefined
。
这归结为箭头函数破坏了继承。
我是不是遗漏了什么,或者只是无法像 Java class 那样扩展任意 Node 模块?
具体例子:
我需要 passport-remember-me
将 req
对象暴露给 _issue
方法。我试图做的是扩展该功能 (RememberMe.Strategy
),修改 _issue
功能,然后将实际业务逻辑委托给原始父 class' 功能:
// 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
上下文。为什么会这样??
父class长什么样(第三方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
绑定到定义函数的上下文。如果你在任何函数之外定义它,那么 this
将是全局对象,或者如果在严格模式下 undefined
。
这归结为箭头函数破坏了继承。