-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest-privates.html
88 lines (64 loc) · 2.32 KB
/
test-privates.html
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
81
82
83
84
85
86
87
88
<script>
//This is just for the purposes of this test file; in a real application you should use an AMD loader
//such as this: https://github.com/cujojs/curl
var simpleoo;
function define(dependencies, definition) {
simpleoo = definition();
}
</script>
<script src="simpleoo.js"></script>
<script>
var log = console.log;
var extend = simpleoo.extend;
var mixin = simpleoo.mixin;
var deepCopy = simpleoo.deepCopy;
//http://tc39wiki.calculist.org/es6/symbols/
(function() {
"use strict";
var secret = 'secret code';
var isOlderBrowser = false;
function Symbol(internalName, isPrivate) {
this.internalName = internalName;
}
Symbol.prototype.toString = function() {
var ret = secret + this.internalName;
//MAY NOT WANT TO AUTOMATICALLY SUPPORT OLDER BROWSERS...FOR THIS EXAMPLE, WE DON'T WANT THEM TO BE ABLE TO MODIFY THEIR
//SCORE...SO IF THERE'S A WAY TO MAKE IT FOOLPROOF ON ES5 BUT NOT EARLIER, THEN THERE SHOULD BE AN OPTION TO *NOT*'
//SUPPORT IT ON OLDER BROWSERS
//start with _private so that older browsers that don't support Object.defineProperty to create non-enumerable properties
//will still see a clear indication that the property is private
if (!Object.defineProperty) return '_private_' + ret;
return ret;
}
function PrivateProperty(obj, name) {
this.name = name;
//We might not need this, but we should have some way of checking to see if the property was actually added to the
//object using defineProperty before allowing it to be used
this.initialized = false;
}
PrivateProperty.prototype = makePrototype(PrivateProperty, extend(Symbol.prototype));
var score = new Symbol('score', true);
function definePrivateProperty(obj, propName, defaultVal) {
if (defaultVal == undefined) defaultVal = null;
//the property will not be enumerable or configurable, since those
//default to false
Object.defineProperty(obj, secret + propName, {value:defaultVal, writable:true});
}
window.Player = function Player() {
definePrivateProperty(this, 'score');
this[score] = 0;
increaseScore(this, 1);
}
Player.prototype.getScore = function() {
return this[score];
}
function increaseScore(player, n) {
player[score] += n;
}
})();
var log = console.log;
var player = new Player();
log(player.getScore());
log(player.score);
log(player);
</script>