简体   繁体   English

Java一个接一个的方法调用

[英]Javascript One after another method call

I want to javascript validation for __NodeJS Rest API__ , but my problem is; 我想对__NodeJS Rest API__进行JavaScript验证,但是我的问题是;

Validator Class 验证者类别

class Checks {

 constructor() {

 }

 object(field) {
  return field;
 }

 keys(field) {
   if(typeof field === "string") {
    return true;
   }
  return false;
 }

}

module.exports = Validator;

and I want to use 我想用

Validator.validate(field).string()

but error code: 但错误代码:

You can assign field as a property of the current instance then return the this for chaining methods. 您可以将field分配为当前实例的属性,然后为链接方法返回this

class Validator {

 constructor() {
   this.field = null;
 }

 validate(field) {
   this.field = field;
   return this;
 }

 string(field) {
   return typeof this.field === "string";
 }

}

module.exports = Validator;

//usage
const Validator = require('path/to/Validator');
new Validator().validate(field).string();

You can change like, 您可以像这样更改

class Validator {

 constructor() {

 }


 validate(field) {
   if(typeof field === "string") {
    return true;
   }
  return false;
 }

}

module.exports = Validator;

And make a call like, 打个电话,

Validator.validate(field)

Or simply change the validate function as, 或者只是将validate函数更改为

validate() {
  return this;
 }

And call it like, 然后这样称呼它,

Validator.validate().string(field)
//validator-factory.js

class ValidatorFactory {

  static validate(field) {
    return new Validator(field);
  }

}

class Validator {

 constructor(field) {
   this.field = field;
 }

 string() {
   if(typeof this.field === "string") {
    return true;
   }
  return false;
 }

}

module.exports = ValidatorFactory;

Then, import ValidatorFactory & use as follows 然后,导入ValidatorFactory并按以下方式使用

var ValidatorFactory = require('./validator-factory');
ValidatorFactory.validate(field).string();

Note the use of static keyword in ValidatorFactory & validate returns new instance of Validator class every time. 请注意,在ValidatorFactory使用static关键字,并且validate每次都会返回Validator类的新实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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