繁体   English   中英

遍历一个函数的属性,可能吗?

[英]loop throught a function properties, possible?

我想遍历函数的属性,这是我的尝试:

 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()方法返回一个布尔值,指示对象是否具有指定的属性作为其自己的属性(而不是继承它)。”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM