简体   繁体   English

javascript defineProperty使属性不可枚举

[英]javascript defineProperty to make an attribute non enumerable

I'm trying to use defineProperty to made attributes not appear in for...in cycle, but it doesn't work. 我正在尝试使用defineProperty使属性不出现在...循环中,但它不起作用。 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);
}

Item does not have a property named nonEnum ( check it out ). Item没有名为nonEnum的属性( 检查出来 )。 It is a (constructor) function that will create an object that has a property called nonEnum . 它是一个(构造函数)函数,它将创建一个具有名为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 jsFiddle演示

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

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