【问题标题】:node.js object extended with a mixin can't find function after instantiation用mixin扩展的node.js对象在实例化后找不到函数
【发布时间】:2018-02-14 16:41:06
【问题描述】:

我已经设法为我的 mixin 设置了一个相当复杂的设置(尽管这是 Code Review 的问题),如下所示:

TooManyCaps.js

module.exports = {
  labelCopyCaps: () => {
    if (this.release.tracks.length > 1) {
      if (_this._notEnoughLowercase(this.release.title)) {
        this._recordError(release, 'LABELCOPYCAPS');
      } else {
        this.release.tracks.some( (track) => {
          if (this._lowerCaseCount(track.label_copy)) {
            this._recordError(release, 'LABELCOPYCAPS');
            return true;
          }
        });
      }
    }
  },
  _notEnoughLowercase: (str) => {
    if ((str.match(/[a-zA-Z]/g)||[]).length > 3
        && str.length - str.replace(/[a-z]/g, '').length) {
      return true;
    }
    return false;
  }
};

然后我有一个可以将其用作混合的对象:

Rule.js

class Rule {
  constructor(release) {
    this.release = release;
    this.errors = [];
  }

  _recordError(error, options) {
    this.errors.push({
      release_id: this.release.id,
      rule: error,
      options: options,
    });
  }
}

module.exports = Rule;

然后我有一个索引页面将它们连接在一起

index.js

const TooManyCaps = require('./TooManyCaps');
const Rule = require('./Rule');
Object.assign(Rule.prototype, [TooManyCaps]);
module.exports = Rule;

然后是我的程序的主要开始,该程序会进行一些实例化:

'use strict';
const RuleValidator = require('./job/validation/RuleValidatorMixin');
const Rule = require('./job/validation/rulesmixins/rules/index');

// some logic that's a loop
arr.forEach((value) => {
  new RuleValidator(new Rule(value)).validate();
}

在 validate() 中我有:

  validate() {
    console.log('VALIDATE');
    this.rule.labelCopyCaps();
    // console.log(this.rule);
  }

但是当我运行它时,我得到:

this.rule.labelCopyCaps is not a function

那么我哪里出错了?

【问题讨论】:

    标签: javascript node.js ecmascript-6 mixins


    【解决方案1】:

    Object.assign 不带数组:

    Object.assign(Rule.prototype, [TooManyCaps]);
    //                            ^           ^
    

    应该只是

    Object.assign(Rule.prototype, TooManyCaps);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-14
    • 2017-05-13
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2018-08-01
    • 2014-05-04
    • 1970-01-01
    相关资源
    最近更新 更多