Skip to content

Instantly share code, notes, and snippets.

@apphp
Created January 27, 2014 09:54
Show Gist options
  • Save apphp/8645882 to your computer and use it in GitHub Desktop.
Save apphp/8645882 to your computer and use it in GitHub Desktop.
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.
// source: http://www.apphp.com/index.php?snippet=javascript-define-class-private-memebrs
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment