如何在JavaScript中定义类私有成员

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在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.
  1. <script language="javascript">
  2. FormValidator = function(){
  3.  
  4. // private data member (property)
  5. var _digits = "0123456789";
  6.  
  7. // public data member (property)
  8. this.digits = "0123456789";
  9.  
  10. // private data function (method)
  11. var _isEmpty = function(s){ return((s==null)||(s.length==0))};
  12.  
  13. // publick data function (method)
  14. this.isEmpty = function(s){ return((s==null)||(s.length==0))};
  15. }
  16.  
  17. /* create a new instance of Validator object */
  18. var jsFormValidator = new FormValidator();
  19.  
  20. /* wrong access, errors will be produced */
  21. alert(jsFormValidator._digits);
  22. alert(jsFormValidator._isEmpty());
  23.  
  24. /* valid access */
  25. alert(jsFormValidator.digits);
  26. alert(jsFormValidator.isEmpty());
  27. </script>

以上是关于如何在JavaScript中定义类私有成员的主要内容,如果未能解决你的问题,请参考以下文章