简体   繁体   English

实例化许多JavaScript对象的最佳方法是什么?

[英]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.

相关问题 在Javascript中创建对象数组的最佳方法是什么? - What is the best way to create an array of objects in Javascript? 实例化JavaScript对象时的最佳做法是什么? - What best practice when instantiating a JavaScript object? 为网站自动化生成JavaScript测试对象的最佳方法是什么? - What is the best way to generate JavaScript test objects for website automation 从对象数组中查找对象索引的最佳方法是什么 - javascript - What is the best way to find index of object from array of objects - javascript 在 Javascript 中获取/设置对象深层属性的最佳方法是什么? - What is the best way to get/set an objects deep property in Javascript? 从两个单独的JavaScript对象合并属性的最佳方法是什么? - What is the best way to merge properties from two separate JavaScript objects? 在javascript中更改对象数组顺序的最佳方法是什么 - What is the best way to change the order of array of objects in javascript Javascript 根据数组中的字符串列表过滤对象的最佳方法是什么? - Javascript what is the best way to filter objects based on a list of strings in an array? 在javascript中查询json对象/数组的最佳方法是什么? - What is the best way to query json objects/arrays in javascript? 将JavaScript对象序列化为XML的最佳方法是什么? - What's the best way to serialize JavaScript objects to XML?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM