[英]How do I make the properties of a JS object non-enumerable?
我想讓過濾器不可枚舉。
目前,如果您嘗試以下操作來創建新過濾器,則會顯示所有鍵;
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
}
});
您應該在原型上定義屬性。 否則,您只是為過濾器對象定義它,而不是為您創建的每個實例定義它:
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.