在构造函数中创建函数会比引用原型函数使用更多内存吗?
我想这确实是一个关于浏览器实现闭包的问题。我知道在 JavaScript 中模拟类功能的多种方法,包括使用各种库。这更多的是一个关于资源的问题。
以这种方式创建函数是否每次调用时都会创建 public_function
函数的新副本?根本问题是:这样做是否会比将函数添加到 MyObject.prototype 中使用更多的 RAM?
function MyObject(){
this.public_function = function(){
//... do something
}
}
Possible Duplicate:
JavaScript: Setting methods through prototype object or in constructor, difference?
I guess this is a question about the browsers implementation of closures really. I know about the numerous ways to emulate Class-like functionality within JavaScript including using various libraries. This is more a question about resources.
Does creating a function in this manner create a new copy of public_function
function each time it is called? the underlying question is: Does doing it this way use more RAM than adding the function to MyObject.prototype
?
function MyObject(){
this.public_function = function(){
//... do something
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。
如果不出意外的话,这需要在
new MyObject()
创建的每个对象上都有一个槽,而不是在原型上有一个槽。但当然,还有其他东西:匿名函数创建一个闭包,捕获定义它的范围。再说一遍,必须为 MyObject 创建的每个对象存储该信息。
这是否真的重要将取决于您创建的对象数量...
另请参阅:
Yes.
If nothing else, this requires a slot on every object created by
new MyObject()
rather than a single slot on the prototype.But of course, there is something else: the anonymous function creates a closure, capturing the scope in which it is defined. And again, that has to be stored for every object created by MyObject.
Whether this actually matters will depend on how many objects you create...
See also:
对于具有多个实例的类,构造函数中定义的匿名函数将为每个实例创建一个新的函数副本。
另一种不使用原型的方法是定义一个静态函数并将其分配给成员。例如:
For a class that has mulitipul instances, an anonymous function defined in constructor will create a new copy of function for each instance.
another way without using prototype is that define a static function and assign it to the member. For example: