[英]What is the best way of instantiating many JavaScript objects?
I need to create many instances of a specific class in a single page, and I'm wondering if the way that I define the methods of that class will have an impact on the page's performance. 我需要在单个页面中创建特定类的许多实例,我想知道我定义该类方法的方式是否会影响页面的性能。 Does it matter whether I define the methods like this:
我是否定义这样的方法是否重要:
function Foo(h, l) {
this.h = h;
this.l = l;
}
Foo.prototype.bar = function(x) {
// do stuff
}
Or this: 或这个:
function Foo(h, l) {
this.h = h;
this.l = l;
this.bar = function(x) {
// do stuff
};
}
Does one offer performance benefits over the other if I have to create many instances of this class (and if the class has several other methods)? 如果我必须创建这个类的许多实例(如果该类有其他几种方法),那么它是否提供了性能优势? Or is there another, better way I should be using?
或者我应该使用另一种更好的方法吗? Assume that I instantiate all of the objects using
new Foo(h,l);
假设我使用
new Foo(h,l);
实例化所有对象new Foo(h,l);
The first one is much preferred. 第一个是首选。 In that case, there is only one definition of the
bar
function, and all Foo
objects share it. 在这种情况下,
bar
函数只有一个定义,所有Foo
对象都共享它。 In the second case, the bar
function is being declared every single time, and each object contains their own version of it. 在第二种情况下,
bar
函数每次都被声明,每个对象都包含它们自己的版本。
最好使用第一种方法,因为每个Foo
实例都共享相同的bar
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.