如何在JS es6类中实现多个方法?

时间:2018-07-31 20:12:59

标签: javascript class ecmascript-6

我有一类在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;
  }
}

3 个答案:

答案 0 :(得分:2)

使用fluent methods / chainable methods创建一个类,该类返回this,它是该类本身的一个实例,当您最终根据规则运行验证时,调用{{1 }},它将作为返回结果的最终方法:

.validate()

答案 1 :(得分:2)

尝试类似的操作-在实例化时将对象验证为一个属性,从每个验证调用返回this,在验证时,为对象分配一个isValid属性(如果有)还不是false)。请注意,您最终需要访问isValid属性才能检索布尔值。

class Validator {
  constructor(obj) {
    this.obj = obj;
    this.isValid = true;
  }
  selector(sel) {
    this.sel = sel;
    return this;
  }
  minLength(min) {
    if (this.isValid) this.isValid = this.obj[this.sel].length >= min;
    return this;
  }
  maxLength(max) {
    if (this.isValid) this.isValid = this.obj[this.sel].length <= max;
    return this;
  }
}

const test = new Validator({firstName: 'foobar'}); // 6 chars: invalid
console.log(test.selector("firstName").minLength(2).maxLength(5).isValid);
const test2 = new Validator({firstName: 'fooba'}); // 5 chars: valid
console.log(test2.selector("firstName").minLength(2).maxLength(5).isValid);
const test3 = new Validator({firstName: 'f'}); // 1 char: invalid
console.log(test3.selector("firstName").minLength(2).maxLength(5).isValid);

答案 2 :(得分:0)

这是构建器模式(一种)。您可能需要定义一个具有minLength和maxLength函数的单独的类。这些函数将在构建器上设置一些状态,并返回this(构建器本身)或新的构建器,该复制器是this的副本。然后,您将在构建器上具有一些finalize函数,该函数查看状态,根据最小/最大值处理所有逻辑,并返回布尔值。

相关问题