首页 > 解决方案 > 如何在 JS es6 类中实现多个方法?

问题描述

我有一类在 JS 中创建的验证:

let test = new Validator(req.body);

现在我想测试一些东西,也许这个对象中的特定键是 2-5 字符长度,我会这样做:

let myBoolean = test.selector("firstName").minLength(2).maxLength(5);
// firstName is like: req.body.firstName

以及如何在课堂上做到这一点?

编辑

我做了这样的事情:

audit.isLength({selector: "from", gte: 2, lte: 35})

class Validator {

  constructor(obj) {
    this.obj = obj;
    this.isValid = true;
  }

  isExists(sel) {
    if (typeof this.obj[sel] === "undefined") return false;
    return true;
  }

  isLength(info) {
    let sel = this.obj[info.selector];
    if (typeof sel === "undefined") return false;
    if (info.gte) {
      if (sel.length<info.gte) return false;
    }
    if (info.lte) {
      if (sel.length>info.lte) return false;
    }
    if (info.gt) {
      if (sel.length<=info.gt) return false;
    }
    if (info.lt) {
      if (sel.length>=info.lt) return false;
    }
    return true;
  }
}

标签: javascriptclassecmascript-6

解决方案


创建一个具有流利方法/可链接方法的类,该 returnthis是该类本身的一个实例,当您最终根据规则运行验证时, call.validate()将作为最终方法返回结果:

class Validator {
  constructor (body) {
    this._body = body;
  }
  
  selector(str) {
    this._selector = str;
    return this;
  }
  
  minLength(num) {
    this._minLength = num;
    return this;
  }
  
  maxLength(num) {
    this._maxLength = num;
    return this;
  }
  
  validate() {
    // run your validation logic here and return true or false accordingly
    return true
  }
}

const req = { body: 'body' };
const test = new Validator(req.body);
const myBoolean = test
  .selector('firstName')
  .minLength(2)
  .maxLength(5)
  .validate();
  
console.log('rules:');
console.log(test);
console.log(`result: ${myBoolean}`);


推荐阅读