Posted By

apphp-snippets on 01/29/14


Tagged

javascript class members private apphp


Versions (?)

How To Define Class Private Members in JavaScript


 / Published in: JavaScript
 

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

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.

  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>

Report this snippet  

You need to login to post a comment.