Javascript私有方法 - 什么是内存影响? [英] Javascript private methods -- what is the memory impact?

查看:94
本文介绍了Javascript私有方法 - 什么是内存影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一段代码,我试图在闭包中隐藏一些私有变量。事情是环境在内存方面受到相当的限制,所以我也关心保持类的总体足迹低。

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?

我的代码看起来像这样

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;
}

....继续定义所有其余方法。 / p>

.... 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.

这篇关于Javascript私有方法 - 什么是内存影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆