Skip to content

Instantly share code, notes, and snippets.

@sixthgear
Created August 11, 2011 21:58
Show Gist options
  • Select an option

  • Save sixthgear/1140900 to your computer and use it in GitHub Desktop.

Select an option

Save sixthgear/1140900 to your computer and use it in GitHub Desktop.
Javascript Encapsulation
var obj = function(s) {
// private member
v1 = "priv: " + s;
// public member
this.v2 = "pub: " + s;
// private methods can access private members
function m1() {
return "private method: " + v1;
};
// privileged methods can also access private members
this.m2 = function() {
return "privileged method: " + v1;
};
// privileged methods can call private methods
this.m3 = function() {
return "privileged method: " + m1();
};
}
// public methods can access public members
obj.prototype.m4 = function() {
return "public method: " + this.v2;
}
// public methods can access privileged methods
obj.prototype.m5 = function() {
return "public method: " + this.m2();
}
var o = new obj("hello");
console.log(o.v1); // undefined (can't access private members publically)
console.log(o.v2); // pub: hello
console.log(o.m1()); // TypeError (can't call private methods publically)
console.log(o.m2()); // privileged method: priv: hello
console.log(o.m3()); // privileged method: private method: priv: hello
console.log(o.m4()); // public method: pub: hello
console.log(o.m5()); // public method: privileged method: priv: hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment