Skip to content

Instantly share code, notes, and snippets.

@gigafied
Created February 28, 2012 22:52
Show Gist options
  • Save gigafied/1935833 to your computer and use it in GitHub Desktop.
Save gigafied/1935833 to your computer and use it in GitHub Desktop.
Private vars with Rosy
var red = red || {};
red.Module = Class.extend({
init : function (aVal, bVal) {
/* All private variables have to live here. */
var a;
var b;
var _Module = Class.extend({
init : function (aVal, bVal) {
a = aVal;
b = bVal;
},
log : function () {
console.log(a, b);
}
});
return new _Module(aVal, bVal);
}
});
red.SubModule = red.Module.extend({
init : function (aVal, bVal) {
this.sup(aVal, bVal);
}
});
var instance1 = new red.Module("instance1A", "instance1B");
var instance2 = new red.Module("instance2A", "instance2B");
var subInstance1 = new red.Module("subInstance1A", "subInstance1B");
var subInstance2 = new red.Module("subInstance2A", "subInstance2B");
instance1.log(); // Outputs: "instance1A, instance1B"
instance2.log(); // Outputs: "instance2A, instance2B"
subInstance1.log(); // Outputs: "subInstance1A, subInstance1B"
subInstance2.log(); // Outputs: "subInstance2A, subInstance2B"
@gigafied
Copy link
Author

The downside to this, is that there is additional overhead everytime you create a new instance of Module. There is no way around this if you want your "private"/closured vars on a per instance basis.

@gigafied
Copy link
Author

Also requires modification of base/class.js (line 62), to:

return this.init.apply(this, arguments);

@potench
Copy link

potench commented Feb 29, 2012

ah cool - tried it out here and it does work
http://jsfiddle.net/Ktn23/1/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment