假设我有以下代码段:
function Airplane(id) {
this.id = id;
}
var air1 = new Airplane(234);
var air2 = new Airplane(235);
var air3 = new Airplane(236);
有没有办法让飞机对象的总数创建为Airplane.getCreatedLength()
?
答案 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