我想遍历函数属性,这是我的尝试:
var hen = function a() {
this.name = "euler henrique";
this.ID = 55530;
this.REC = 0302;
this.nick = "any will do";
}
for (var p in hen) {
console.log(hen[p]);
}
但这不起作用,即使hen
是a
的实例。有什么建议吗?
一个快速的解决方案可能是将元素作为父对象的属性添加到数组中。例如
var hen = function a() {
this.name = "euler henrique";
this.ID = 55530;
this.REC = 0302;
this.nick = "any will do";
this.info = [this.name, this.id, this.REC, this.nick];
}
然后像任何数组一样循环遍历这个数组。
var myHen = new Hen();
for(var x = 0; x < myHen.info; x ++)
{
info = myHen.info[x];
if(info)
{
console.log(info);
}
}
不确定这是否是你想要的,让我知道这是否不是你需要的,我很乐意分享一些其他的想法。
如果您创建对象的实例,则可以执行此操作:
var Hen = function() {
this.name = "euler henrique";
this.ID = 55530;
this.REC = 0302;
this.nick = "any will do";
}
var myHen = new Hen();
for (let prop in myHen) {
if (myHen.hasOwnProperty(prop)) {
console.log(prop);
}
}
您可以使用函数构造函数创建对象:new YourFunctionName();
来自 MDN:"hasOwnProperty(( 方法返回一个布尔值,指示对象是否将指定的属性作为自己的属性(而不是继承它(。