Dynamically calling private methods of a class?
-
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 -
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 -
This is really a waste of time. Private methods cannot be called dynamically.Anonymous
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!