我正在使用javascript,想知道构造函数内部的对象数量。
我有这个:
var EventData = function(ID, Name, StartDate, StartTime, EndDate, EndTime, Location, Notes){
this.type = "event";
this.id = ID;
this.name = Name;
this.startDate = StartDate;
this.startTime = StartTime;
this.endDate = EndDate;
this.endTime = EndTime;
this.location = Location;
this.notes = Notes;
};
EventData.prototype.count = function(){
return //some code;
};
而且我想这样称呼:
var Start = function(){
var thisEventData = new EventData(1,"Bill", 1,1,1,1, "Home", "N/A");
console.log(thisEventData.count());
};
其中thisEventData.count()将返回10。
在这种情况下,最自然的方法是将参数计数存储在某些属性中(可能是私有的)。我不确定为什么需要这个,但是,是的,像这样:
var EventData = function (ID, Name, StartDate, StartTime, EndDate, EndTime, Location, Notes) {
this._paramsCount = arguments.length;
this.type = "event";
this.id = ID;
this.name = Name;
this.startDate = StartDate;
this.startTime = StartTime;
this.endDate = EndDate;
this.endTime = EndTime;
this.location = Location;
this.notes = Notes;
};
EventData.prototype.count = function () {
return this._paramsCount;
};
UPD。根据已编辑的问题,您似乎想计算实例自己的属性数量。在这种情况下,您将使用方便的Object.keys
方法,该方法返回属性名称的数组。
Object.keys
仅将EventData.prototype.count = function () {
return Object.keys(this).length;
};
对象的属性作为带有EventData
的数组,然后得到数组的长度?
Object.keys
如果您想了解规范参数的数量,请根据需要使用EventData.prototype.count = function(){
return Object.keys(this).length;
};
属性:
Function.length
或
Function.length
请注意,由于它会从构造方法对象中推断计数,因此不会计算其他参数(可变参数)。
如果您想知道所构造对象的属性计数,请使用EventData.length
:
thisEventData.constructor.length
这将为您提供own属性的数量(不包括原型链)。
或者如果需要其他东西,也可以编写自己的可定制逻辑,例如,如果您想要non-falsey对象:
Object.keys
要在已接受的答案上加一点:
Object.keys