How To Define Class Private Members in JavaScript


/ Published in: JavaScript
Save to your folder(s)

Class member encapsulation in JavaScript is very important thing and may be implemented with easy. To define private property or method just use var before the definition or this., if you need to give a public access to property or method.


Copy this code and paste it in your HTML
  1. <script language="javascript">
  2. FormValidator = function(){
  3.  
  4. // private data member (property)
  5. var _digits = "0123456789";
  6.  
  7. // public data member (property)
  8. this.digits = "0123456789";
  9.  
  10. // private data function (method)
  11. var _isEmpty = function(s){ return((s==null)||(s.length==0))};
  12.  
  13. // publick data function (method)
  14. this.isEmpty = function(s){ return((s==null)||(s.length==0))};
  15. }
  16.  
  17. /* create a new instance of Validator object */
  18. var jsFormValidator = new FormValidator();
  19.  
  20. /* wrong access, errors will be produced */
  21. alert(jsFormValidator._digits);
  22. alert(jsFormValidator._isEmpty());
  23.  
  24. /* valid access */
  25. alert(jsFormValidator.digits);
  26. alert(jsFormValidator.isEmpty());
  27. </script>

URL: http://www.apphp.com/index.php?snippet=javascript-define-class-private-memebrs

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.