-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitem_47.js
More file actions
41 lines (35 loc) · 1 KB
/
item_47.js
File metadata and controls
41 lines (35 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Never add enumerable properties to 'Object.prototype'
// E.g. 'allkeys'
Object.prototype.allKeys = function() {
var result = [];
for (var key in this) {
result.push(key);
}
return result;
};
// this method pollutes even its own results
({a: 1, b: 2, c: 3}).allKeys(); // ["a", "b", "c", "allKeys"]
// it is more convenient to define 'allkeys' as a function rather than a method
function allkeys(obj) {
var result = [];
for (var key in obj) {
result.push(key);
}
return result;
}
// ES5 provides a mechanism for doing it more cooperatively
// 'Object.defineProperty'
Object.defineProperty(Object.prototype, "allkeys", {
value: function() {
var result = [];
for (var key in this) {
result.push(key);
}
return result;
},
writable: true,
enumerable: false,
configurable: true
});
// Whenever you need to add a property that should not be visible to 'for...in'
// loops, 'Object.defineProperty' is your friend