JavaScript Class pattern
JavaScript April 26th, 2007The following example show a basic template of how to define a JavaScript class. As far as I am aware this is becoming the standard pattern for allowing private and public variables and methods to be implement into a class.
How it works
The function MyClass is the constructor, note the Capitalization of the first letter to denote a constructor. Within the function object we add methods and functions. If we left the object definition as that, then javascript would automatically return the object definition as the result and the methods and properties we added would be public on that object.
Instead we return a new object, not the initial object definition. The new object has all the methods an properties that we wish to expose as public. This is what gets passed back to the calling code. Because of the javascript rules of scope in a function, the new object has access to any variables defined in the initial object definition.
So the first thing we do is create a self variable that is set to this. The public methods can then use the self variable to access any methods or variables that have been assigned to the initial object definition’s ‘this’. In addition any other vars e.g. private1 are accessible by the public functions also.
This all works because javascript closure causes the ‘new object’ to keep a reference to the ‘initial object’ even after the constructor function has returned.
1: // myobject.js
2:
3: function MyClass(param1)
4: {
5: // Private Section
6:
7: // create a reference to this, called self so the self variable
8: // can then be accessed by the public object
9: var self = this;
10:
11:
12: // Totally private variables are defined with var
13: var private1 = "fred";
14:
15:
16: // Private variable that can be accessed by the implementation of the public object only
17: this.private2 = "private2 data";
18:
19:
20: // private functions
21: this.privateMethod1 = function()
22: {
23: alert("private Method 1 called : private1 variable value is (" + private1 + ")");
24: }
25:
26:
27: // public Object defintion which gets returned to the outside world.
28: return {
29: publicVariable : 10,
30:
31: publicMethod1 : function()
32: {
33: alert("public method 1 called");
34: },
35:
36: publicMethod2 : function()
37: {
38: alert("public method 2 called about to call privatemethod1");
39: // Note: this refers to the current object about to returned
40: // to access the private methods, we need to use 'self'
41: self.privateMethod1();
42: alert("Private Variable (private1):" + private1);
43: alert("Private Variable (private2):" + self.private2);
44: }
45:
46: };
47:
48: };
49:
50: // static members and properties
51: MyClass.prototype.staticFunction = function()
52: {
53: alert("Hello from a static function");
54: }
55:
56: MyClass.prototype.staticVar = 69;
A test page to prove the scoping of the private and public members and properties.
1: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
2: <html>
3: <head>
4: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
5: <title>Untitled Document</title>
6:
7: <script src="myobject.js" type="text/javascript"></script>1:2:3: <link href="./css/ext-all.css" media="screen" rel="stylesheet" type="text/css">4:5:6: <script type="text/javascript">7: var test = new MyClass("Private1 passed in by constructor");8:9: function callPublic1()10: {11: test.publicMethod1();12: }13:14: function callPublic2()15: {16: test.publicMethod2();17: }18:19: function tryCallPrivateMethod1()20: {21: test.privateMethod1();22: }23:24: function tryAccessPrivateVariable()25: {26: alert("Private 1:" + test.private1);27: alert("Private 2:" + test.private2);28: }29:30: function tryAccessPublicVariable()31: {32: alert(test.publicVariable);33: }34:35: function callStaticFunction()36: {37: MyClass.prototype.staticFunction();38: }39:40: function getStaticVariable()41: {42: alert(MyClass.prototype.staticVar);43: }44:45:46:</script>
8:
9: </head>
10:
11: <body>
12: <a href="javascript:callPublic1();">Call Public Method 1</a><br/>
13: <a href="javascript:callPublic2();">Call Public Method 2</a><br/>
14: <br>
15: <a href="javascript:tryCallPrivateMethod1();">Try and call PrivateMethod1</a> This should fail<br/>
16: <a href="javascript:tryAccessPrivateVariable();">Try and access private variable</a> This should return undefined as the variable does not exist<br/>
17: <a href="javascript:tryAccessPublicVariable();">Try and access public variable</a> This should display 10<br/>
18: <br>
19: <a href="javascript:callStaticFunction();">Call static function on class prototype</a><br/>
20: <a href="javascript:getStaticVariable();">Get static variable from class prototype</a> Should display 69<br/>
21: </body>
22: </html>
Recent Comments