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
[View All Snippets]
var
before the definition or
this.
, if you need to give a public access to property or method.
[View All Snippets]
Show Plain Text »
- <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>