This repository has been archived by the owner on Dec 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
protect.js
80 lines (70 loc) · 2.21 KB
/
protect.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
(function () {
'use strict';
// The protect object
this.protect = function (_O) {
var callDepth = 0; // Stores the call depth of the current execution
var locked = function () {
return !callDepth;
};
var O = _O.prototype || _O; // Protect the prototype, if there is one
Object.keys(O).forEach(function (key) {
var value = O[key]; // The original property value
var isFunction = typeof value === 'function';
if (key.indexOf('_') === 0) { // Should the object be protected
Object.defineProperty(O, key, {
get: function () {
if (locked()) {
return undefined;
}
else {
if (!isFunction) {
return value;
}
return function () {
return value.apply(this, arguments);
};
}
},
set: function () {
if (!locked()) {
value = arguments[0];
isFunction = typeof value === 'function';
}
},
enumerable: false // Remove from Object.keys
});
}
else { // Allow functions to retrieve private properties
Object.defineProperty(O, key, {
get: function () {
if (!isFunction) {
return value;
}
return function () {
var result;
try {
callDepth++;
result = value.apply(this, arguments);
}
catch (e) {
throw e;
}
finally {
callDepth--;
}
return result;
};
},
set: function () {
value = arguments[0];
isFunction = false; // New functions cannot unlock private properties
}
});
}
});
};
// Make it available for both Node and Browser
if(typeof module !== 'undefined' && module.exports) {
module.exports = this.protect;
}
}).call(this);