簡體   English   中英

實例化后,使用mixin擴展的node.js對象無法找到函數

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

我已經為我的mixins獲得了一個相當復雜的設置(盡管這是代碼審查的問題),如下所示:

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

那我哪里出問題了?

Object.assign不采用數組:

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

應該只是

Object.assign(Rule.prototype, TooManyCaps);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM