node.js - 使用 OOP 扩展 Node.js 模块

标签 node.js oop inheritance passport.js prototypal-inheritance

我是否遗漏了什么,或者是否无法像 Java 类那样扩展任意 Node 模块?

具体示例:

我需要 passport-remember-mereq 对象公开给 _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/

相关文章:

node.js - 适用于 Windows 和 *nix 的通用 Node.js $INIT_CWD

php - 克隆如何创建单例的新版本?

html - CSS 中继承和特殊性的混淆

inheritance - 如何继承odoo v8上的_constraints?

node.js - node express es6 sinon stub 中间件不工作

javascript - 高级原型(prototype)函数

java - 变更传播规则和影响分析

javascript - 合并两个对象但保持继承

javascript - 如何部署 Angular/Node 应用程序

Python:将函数作为参数传递以初始化对象的方法。 Pythonic 与否?