Encapsulation
The fundamental goal for encapsulation is to control what variables/functions are available for external access. The mechanism for doing this in JavaScript is a closure. By wrapping the class definition in a closure it is possible to have private functions accesible only this class, since objects outside of the closure won't be in the same scope.
(function(){
//constructor
window.JSObject = function(){
this.publicInstanceVar1 = 1
};
// public function
JSObject.prototype.foo = function(){
privateFunction.apply(this); //call private function
};
//private function
function bar(){}
var privateClassVar1 = "1"
}());
The constructor must be attached to the window, or declared outside of the closure, otherwise it will not be accessible externally. The public method is added to the object prototype. The private method is a function declared inside of the closure and must be called using apply or call to maintain the consistency the this variable.
Inheritance
Inheritance for a prototype object is very simple. Assigning a new parent object to the prototype of the inheriting object will do the trick.
(function(){
window.Child = function(){};
Child.prototype = new Parent();
}());
The instance variables and public functions are now available in the child class. The private methods and private class variables will not be inherited.
Click Here to see a demo.