javascript defineProperty to make an attribute non enumerable

夙愿已清 提交于 2019-12-01 15:57:46

问题


I'm trying to use defineProperty to made attributes not appear in for...in cycle, but it doesn't work. Is this code correct?

function Item() {
    this.enumerable = "enum";
    this.nonEnum = "noEnum";
}
Object.defineProperty(Item, "nonEnum", { enumerable: false });

var test = new Item();

for (var tmp in test){
    console.log(tmp);
}

回答1:


Item does not have a property named nonEnum (check it out). It is a (constructor) function that will create an object that has a property called nonEnum.

So this one would work:

var test = new Item();
Object.defineProperty(test, "nonEnum", { enumerable: false });

You could also write this function like this:

function Item() {
    this.enumerable = "enum";
    Object.defineProperty(this, "nonEnum", { 
        enumerable: false, 
        value: 'noEnum' 
    });
}

jsFiddle Demo



来源:https://stackoverflow.com/questions/10269652/javascript-defineproperty-to-make-an-attribute-non-enumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!