Return to Snippet

Revision: 65851
at January 29, 2014 21:20 by apphp-snippets


Initial Code
<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>

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

Initial Description
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.

Initial Title
How To Define Class Private Members in JavaScript

Initial Tags
javascript, class

Initial Language
JavaScript