简体   繁体   中英

node.js object extended with a mixin can't find function after instantiation

I've managed to get a fairly complex setup (though that's a question for Code Review) for my mixins that looks like this:

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;
  }
};

I then have an Object that would use this as a 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;

i then have an index page that joins them together

index.js

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

And then my main start of the program that does some instantiating of things:

'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();
}

and within validate() I have:

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

But then when I run this, I get:

this.rule.labelCopyCaps is not a function

So where have i gone wrong?

Object.assign does not take an array:

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

should be just

Object.assign(Rule.prototype, TooManyCaps);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM