Compact and efficient JavaScript encapsulation

Here is one more Javascript encapsulation implementation. The idea followed is from the link published in hacker news.  The implementation is more compact and efficient.

function class(options){
var constructor = options.constructor,
public = options.public,
private = options.private,
key;


function hiddenClass(){}

var hp = hiddenClass.prototype = {};

function publicClass(){
var obj = new hiddenClass();
constructor && constructor.apply(obj, arguments);
Object.defineProperty(this, 'obj', {value : obj});
}

var pp = publicClass.prototype = {};

for(key in private){
if(private.hasOwnProperty(key)){
hp[key] = private[key];
}
}

for(key in public){
if(public.hasOwnProperty(key)){
var val = public[key];
hp[key] = pp[key] = val;

if(typeof val === 'function'){
pp[key] = function(){
return hiddenClass.prototype[key].apply(this.obj, arguments);
}
}
}
}

return publicClass;
}

Here is the example of using “class” function

var c = class({

constructor : function(a, b){
this.a = a;
this.b = b;
},

private: {
helpMe : function(){
console.log(this.a);
}
},

public: {

c : 30,
help : function(){
console.log('Hello');
},
print : function(){
this.help();
this.helpMe();
console.log(this.b);
console.log(this.c);
}
}

});

var o = new c(10, 20);

o.print();
Advertisements

2 thoughts on “Compact and efficient JavaScript encapsulation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s