-
Notifications
You must be signed in to change notification settings - Fork 128
/
break-on-access.js
60 lines (50 loc) · 1.78 KB
/
break-on-access.js
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function breakOn(obj, propertyName, mode, func) {
// this is directly from https://github.com/paulmillr/es6-shim
function getPropertyDescriptor(obj, name) {
var property = Object.getOwnPropertyDescriptor(obj, name);
var proto = Object.getPrototypeOf(obj);
while (property === undefined && proto !== null) {
property = Object.getOwnPropertyDescriptor(proto, name);
proto = Object.getPrototypeOf(proto);
}
return property;
}
function verifyNotWritable() {
if (mode !== 'read')
throw "This property is not writable, so only possible mode is 'read'.";
}
var enabled = true;
var originalProperty = getPropertyDescriptor(obj, propertyName);
var newProperty = { enumerable: originalProperty.enumerable };
// write
if (originalProperty.set) {// accessor property
newProperty.set = function(val) {
if(enabled && (!func || func && func(val)))
debugger;
originalProperty.set.call(this, val);
}
} else if (originalProperty.writable) {// value property
newProperty.set = function(val) {
if(enabled && (!func || func && func(val)))
debugger;
originalProperty.value = val;
}
} else {
verifyNotWritable();
}
// read
newProperty.get = function(val) {
if(enabled && mode === 'read' && (!func || func && func(val)))
debugger;
return originalProperty.get ? originalProperty.get.call(this, val) : originalProperty.value;
}
Object.defineProperty(obj, propertyName, newProperty);
return {
disable: function() {
enabled = false;
},
enable: function() {
enabled = true;
}
};
};