DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Chara has posted 50 posts at DZone. View Full User Profile

How To Define Class Private Members in JavaScript

01.27.2014
| 1912 views |
  • submit to reddit
<script language="javascript">
FormValidator = function(){
 
    // private data member (property)
    var _digits = "0123456789";
 
    // public data member (property)
    this.digits = "0123456789";
    
    // private data function (method)
    var _isEmpty = function(s){ return((s==null)||(s.length==0))};    
 
    // publick data function (method)
    this.isEmpty = function(s){ return((s==null)||(s.length==0))};        
}
 
/* create a new instance of Validator object */ 
var jsFormValidator = new FormValidator();
 
/* wrong access, errors will be produced */
alert(jsFormValidator._digits);
alert(jsFormValidator._isEmpty());
 
/* valid access */
alert(jsFormValidator.digits);
alert(jsFormValidator.isEmpty());
</script>

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.