如何使JS对象的属性不可枚举?

时间:2017-05-01 21:58:30

标签: javascript

我想让过滤器不可枚举。

目前,如果您尝试以下操作来创建新过滤器,则会显示所有键;

var foo = new filter(3,{a:1});
foo.size; // should be 1
foo.capacity; // should be 3
foo.store('c', 4);
Object.keys(foo); // should be ['a','c']

这是我正在使用的代码。

var filter = function(capacity, value) {

  var store = null;

  (typeof capacity === "number") ? this.capacity = capacity: this.capacity = 3;

  //  Shows the size of the store

  this.size = Object.keys(this).length;

  this.head = null;
  this.tail = null;
  this.store(value);
};

filter.prototype.store = function(value) {

  for (let item in value) {

    if (this[item] === undefined) {
      var node = {
        key: item,
        value: value[item]
      };
      this[item] = node.value;
    } else {
      console.log("this is already present");
      node = {
        key: item,
        value: value[item]
      };
      this.tail.next = node;
      node.prev = this.tail;
      this[item] = node.value;
      return;
    }
  }
  if (this.tail) {
    this.tail.next = node;
    node.prev = this.tail;
  } else {
    this.head = node;
  }

  this.tail = node;
  if (this.size > this.capacity) {
    return
  } else {
    // increase the size counter
    this.size++;
  }
  return;
}

这是为了使属性不可枚举。

Object.defineProperties(filter, {
  "cache": {
    enumerable: false,
    writable: false,
    configurable: false
  },
  "key": {
    writable: true,
    enumerable: false,
    configurable: true
  },
  "size": {
    enumerable: false,
    writable: false,
    configurable: false
  },
  "capacity": {
    enumerable: false
  },
  "head": {
    enumerable: false
  },
  "tail": {
    enumerable: false
  }
});

1 个答案:

答案 0 :(得分:0)

您应该在原型上定义属性。否则,您只是为过滤器对象定义它,而不是为您创建的每个实例定义它:

Object.defineProperties(filter.prototype, {
"cache": {
    enumerable: false,
    writable: false,
    configurable: false
},
"key": {
    writable: true,
    enumerable: false,
    configurable:true
},
"size": {
    enumerable: false,
    writable: false,
    configurable: false 
},
"capacity": {
    enumerable: false
},
"head": {
    enumerable: false
},
"tail": {
    enumerable: false
}
});