使用OOP

时间:2016-07-29 02:19:53

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

我是否遗漏了某些内容,或者只是像扩展Java类那样扩展任意Node模块?

具体示例:

我需要passport-remember-mereq对象公开给_issue方法。我试图做的是扩展该函数(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);
     };
  };

这给了我this内部IWillRememberYou.authenticate以及RememberMeStragety.authenticate内的空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); }; 内容。为什么会发生这种情况?

父类的外观(第三方节点模块)

int? a = 9;
int b = (int)a;

1 个答案:

答案 0 :(得分:1)

执行OO时不要使用箭头功能。这是因为箭头函数是故意设计的,以打破this的工作方式。而是做:

IWillRememberYou.prototype.authenticate = function (req, options) {
  /* .. */
};

请记住,使用箭头函数,您基本上将this绑定到定义函数的上下文。如果您在任何函数之外定义它,那么this将是全局对象,如果是严格模式,则undefined

归结为箭头函数打破了继承。