【问题标题】:Customized property is not enumerable in Javascript?Javascript 中无法枚举自定义属性?
【发布时间】:2016-12-11 17:41:43
【问题描述】:

我定义了自己的“Age”类型,作为“Person”类型的一部分,像这样:

var Age=function(){
    year='1930',
    month='Jan'
}
var Person=function(){
    name='abc',
    age=new Age()
}
var o1=new Person()
console.log(o1.propertyIsEnumerable('age'))

我的期望是,只要 o1 的 age 属性是从“Age”创建的,而它的“年/月”都可以使用字符串作为索引来访问,那么 o1 就是可枚举类型。 但事实上,它打印“false”。

这是为什么,我的理解有误吗?

【问题讨论】:

  • 请重新阅读 JS 教程中关于构造函数和如何设置实例属性的部分。

标签: javascript types properties customization enumerable


【解决方案1】:

您定义的是全局变量而不是属性

var Age=function(){
    year='1930',
    month='Jan'
}
var Person=function(){
    name='abc',
    age=new Age()
}

应该是

var Age=function(){
    this.year='1930';
    this.month='Jan';
}
var Person=function(){
    this.name='abc';
    this.age=new Age();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2013-10-02
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多