How To Define Class Private Members in JavaScript

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.

[View All Snippets]
Show Plain Text »
  1. <script language="javascript">
  2. FormValidator = function(){
  4.     // private data member (property)
  5.     var _digits = "0123456789";
  7.     // public data member (property)
  8.     this.digits = "0123456789";
  10.     // private data function (method)
  11.     var _isEmpty = function(s){ return((s==null)||(s.length==0))};    
  13.     // publick data function (method)
  14.     this.isEmpty = function(s){ return((s==null)||(s.length==0))};        
  15. }
  17. /* create a new instance of Validator object */
  18. var jsFormValidator = new FormValidator();
  20. /* wrong access, errors will be produced */
  21. alert(jsFormValidator._digits);
  22. alert(jsFormValidator._isEmpty());
  24. /* valid access */
  25. alert(jsFormValidator.digits);
  26. alert(jsFormValidator.isEmpty());
  27. </script>
Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory

Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.