Dynamically calling private methods of a class?

  • 0
    I decided to try using the recently introduced private methods on the project. Small sample code:
    class Validate{
    
      constructor({val, type}){
        this.type = type;
        this.val = val;
        this.err = false
      }
    
      #login(){
        return /[a-zA-Z]/.test(this.val);
      }
    
    
      isValidField(){
        const type = '#'+this.type; //login
        return this[type]();
      }  
    }
    
    
      return new Validate({val: 'test', type: 'login'}).isValidField();


    Public methods can be called in this way without problems, but an error occurs with private methods. Is there a way to call private methods dynamically, or is this all a waste of time?
    JavaScript Asher Carney, Aug 24, 2020

  • 2 Answers
  • 0
    No. Only the class itself can operate on private fields containing :



    Only the class which defines the private static field can access the field.


    But you can use getters and setters.
    Anonymous

  • 0
    This is really a waste of time. Private methods cannot be called dynamically.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!