Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, December 13, 2010

Private, privileged and public accessors in Javascript

Definition of Javascript class with accessors mentioned in subject could be pretty easy:

 1 var TestClass = (function(){
2
3
// parameterized constructor
4 TestClass = function(message){
5 // private field
6 var message = message;
7
8
// private function, can't be read by public prototype functions
9 function readMessage(){
10 return message;
11 }
12
13
// privileged method, can access private fields and functions
14 // can be called by public prototypes methods
15 this.getMessage = function(){
16 return readMessage();
17 }
18 }
19
20
// public method
21 TestClass.prototype.displayMessage = function(){
22 return this.getMessage();
23 }
24
25
return TestClass;
26 })();


Usage of such class is following:

1 var test= new TestClass('test');
2 alert(test.displayMessage());