I read David Crockford's way to create private member variables. I created a namespace. For our sake, let's call it ns.
Expand|Select|Wrap|Line Numbers
- ns = { };
Expand|Select|Wrap|Line Numbers
- ns.MyClass = function ( ) { var privateVar; }
Expand|Select|Wrap|Line Numbers
- ns.MyClass.prototype.myProperty = function( value ) {
- if (arugments.length == 1)
- this.privateVar = value;
- else if (arguments.length == 0)
- return this.privateVar;
- else
- throw new Error("myProperty expects 0 or 1 arguments: value");
- }
Expand|Select|Wrap|Line Numbers
- <html>
- <body>
- The value of my property is:
- <script>
- var myClass = new ns.MyClass();
- myClass.privateVar = "Hello World!"; // Shouldn't work, but does??
- document.write(myClass.privateVar + "<br /><br />"); // Shouldn't work but does??
- myClass.myProperty("Hello World!"); // Works, as it should??
- document.wirte(myClass.myProperty() + "<br /><br />"); // Works, as it should??
- </script>
- </body>
- </html>
Expand|Select|Wrap|Line Numbers
- ns = { };
- ns.Class1 = function ( ) { /* some class code */ }
- ns.Class2 = function(init) { /* some class code */}
Thanks in advance for your help!