简体   繁体   中英

Javascript One after another method call

I want to javascript validation for __NodeJS Rest API__ , but my problem is;

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.

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() {
  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

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.

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