如何获取javascript中为类创建的对象总数?

时间:2015-08-07 20:20:30

标签: javascript javascript-objects

假设我有以下代码段:

function Airplane(id) { 
  this.id = id;  
}

var air1 = new Airplane(234);
var air2 = new Airplane(235);
var air3 = new Airplane(236);

有没有办法让飞机对象的总数创建为Airplane.getCreatedLength()

1 个答案:

答案 0 :(得分:3)

您可以跟踪附加到构造函数的属性中的那些:

function Airplane(id) {
  this.id = id;
  Airplane.instances += 1;
}

Airplane.instances = 0;

var air1 = new Airplane(234);
var air2 = new Airplane(235);
var air3 = new Airplane(236);

console.log(Airplane.instances) // 3