简体   繁体   English

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

[英]How do I make the properties of a JS object non-enumerable?

I want to make the filter be non-enumerable. 我想让过滤器不可枚举。

Currently if you try the following to create a new filter, all the keys will show up; 目前,如果您尝试以下操作来创建新过滤器,则会显示所有键;

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']

This is the code I'm using. 这是我正在使用的代码。

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

This is to make the properties non-enumerable. 这是为了使属性不可枚举。

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

You should define the properties on the prototype. 您应该在原型上定义属性。 Otherwise, you're just defining it for the filter object, not for every instance that you create: 否则,您只是为过滤器对象定义它,而不是为您创建的每个实例定义它:

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

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

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