用mixin扩展的node.js对象在实例化后无法找到函数

时间:2018-02-14 16:41:07

标签: javascript node.js ecmascript-6 mixins

我设法为我的mixins设置了一个相当复杂的设置(虽然这是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;
  }
};

然后我有一个Object将它用作mixin:

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

那我哪里出错?

1 个答案:

答案 0 :(得分:1)

dfs(adj, 1, 5)不接受数组:

class Account(models.Model):
    ...
    is_subscribed = models.BooleanField(
        default=False
    )
    monthly_donations = models.PositiveIntegerField(
        default=0
    )
    yearly_donations = models.PositiveIntegerField(
        default=0
    )
    lifetime_donations = models.PositiveIntegerField(
        default=0
    )


class Donation(models.Model):
    related_account = models.ForeignKey(
        Account,
        on_delete=models.CASCADE,
        related_name='donation'
    )
    amount = models.IntegerField()
    date = models.DateField()

应该只是

Object.assign