Tuesday, March 30, 2010

public and private in JavaScript

In order to enjoy programming in JavaScript you have to be at least a little crazy. Take this for example:

function Obj() {
var private = {};

this.publicVar = "inside";
private.privateVar = "inside";
this.getPublic = function() {with(this){with(private){
return publicVar;
}}};
this.getPrivate = function() {with(this){with(private){
return privateVar;
}}};
}

This is, I think, the complete way to emulate Java objects with private and public usage. All other ways are close, but always lack some little oddity that makes it less than pure. Another good thing about this method is it's easily created after parsing Java-like code.

Take this usage for the above object:

var obj = new Obj();
alert(obj.getPublic()); // should alert inside
alert(obj.publicVar); // should alert inside
obj.publicVar = "outside";
alert(obj.publicVar); // should alert outside
alert(obj.getPublic()); // should alert outside

alert(obj.getPrivate()); // should alert inside
alert(obj.privateVar); // should alert undefined
obj.privateVar = "outside";
alert(obj.privateVar); // should alert outside
alert(obj.getPrivate()); // should alert inside

Now, I think I've thought of everything, and everything else, but if anyone out there can break this, or find a shortcut, or challenge it in another means, I would be very grateful. Note, if you want to try breaking it, you don't have to understand the class itself, just how to use it, like I did in the second example.

No comments:

Post a Comment