我正在编写一些代码,试图在闭包中隐藏一些私有变量。问题是环境在内存方面受到了相当大的限制,所以我还关心保持类的整体占用空间较低。
与仅将对象上的所有方法和变量公开相比,使用闭包隐藏私有实例变量和方法有什么影响?使用闭包的实例会比不使用闭包的实例占用更多内存吗?如果是这样,我希望使用多少内存?
我的代码看起来像这样
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
};
相对
function Bar() {
// only define public variables
this.x = 1;
this.y = 3;
}
Bar.prototype.method1 = function () {
// blah;
}
.... 继续并定义所有其余的方法。