使用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。
- 环回 – 扩展内置模型的最简单方法
- Node.Js + Expressjs中的inheritance
- 使用TypeScriptinheritance不起作用浏览器端
- 节点js原型对象'self'var不存储正确的callback上下文
- Node.js EventEmitter和多层次的inheritance
- 检查nodejs中的inheritance
- 问题获取Node.js Express 3.x模板inheritance与Swig通过consolidate.js
- TypeError:超级expression式必须为null或者一个函数,而不是用Babeljs定义的
- 通过调用祖先函数来inheritanceJavaScript