I'm working on a bit of code where I'm attempting to hide some private variables inside closures. The thing is the environment is fairly constrained in terms of memory, so I'm also concerned with keeping the overall footprint of the classes low.
What is the impact of using closures to hide private instance variables and methods when compared to just making all methods and variables on an object public? Would an instance of the one using closures take up more memory than an instance that did not use closures? If so, how much more memory would I expect to use?
my code would look like this
function Foo() {
// private variables
var status = 3;
var id = 4;
...
...
// private methods
var privateMethod = function () {
// do something awesome
}
...
// a whole bunch of these
// public methods
this.publicDriver = function () {
privateMethod();
}
.. a few more of these
};
Versus
function Bar() {
// only define public variables
this.x = 1;
this.y = 3;
}
Bar.prototype.method1 = function () {
// blah;
}
.... Going on and defining all the rest of the methods.
Okay, so from what I can see, constructing the class using the closure case constructs new function objects for each method defined within the constructor, while the prototype assignment way creates a central function that is shared by all instances of the objects. The central instance is then interpreted per object for the proper instance variable references.
I'm guessing each function defined in the closure example refers back to the same stack frame.
Still, in my case, it's a lot more objects floating about.