本文介绍了javascript defineProperty使属性不可枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用defineProperty使属性不出现在循环中的...,但它不工作。

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);
}


推荐答案

没有名为 nonEnum 的属性()。它是一个(构造函数)函数,它将创建一个具有 nonEnum 属性的对象。

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.

将工作:

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

您也可以这样写:

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

这篇关于javascript defineProperty使属性不可枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 05:07