1+ //sharing closures can allow prototypal construction speed times while gaining access to a closure
2+ //and not just any closure, all closures to objects of a given type!
3+ var EphemeronTable = require ( "../lib/overload" ) . EphemeronTable
4+
5+ var MyType
6+ ; ( function ( ) {
7+ var closures = new EphemeronTable ;
8+ MyType = function ( ) {
9+ var myClosures = { views :0 }
10+ closures . set ( this , myClosures )
11+ }
12+ var communicate = MyType . prototype . communicate = function ( object ) {
13+ return closures . get ( object )
14+ }
15+ MyType . prototype . view = function ( ) {
16+ return communicate ( this ) . views ++
17+ }
18+ MyType . prototype . views = function ( ) {
19+ return communicate ( this ) . views
20+ }
21+ MyType . prototype . syncViewsWith = function ( obj ) {
22+ communicate ( this ) . views = communicate ( obj ) . views
23+ }
24+ } ) ( )
25+ var instance_a = new MyType
26+ , instance_b = new MyType
27+
28+ instance_a . view ( )
29+ instance_b . syncViewsWith ( instance_a )
30+ console . log ( instance_b . views ( ) ) //1
31+
32+ //making new prototypes is still possible!
33+ MyType . prototype . doubleView = ( function ( ) {
34+ var communicate = MyType . prototype . communicate
35+ return function ( ) {
36+ communicate ( this ) . views += 2
37+ }
38+ } ) ( )
39+ instance_a . doubleView ( )
40+
41+ //since communicate is available you can still access closures until it isnt
42+ console . log ( MyType . prototype . communicate ( instance_a ) . views ) //3
43+ delete MyType . prototype . communicate
44+
45+ //Communicate is no longer available (kinda like sealing)
46+ try {
47+ console . log ( MyType . prototype . communicate ( instance_a ) ) //fails
48+ }
49+ catch ( e ) {
50+ console . log ( e . stack ) //error!
51+ }
52+
53+ //Compiled functions keep the key!
54+ var instance_c = new MyType
55+ instance_c . syncViewsWith ( instance_a )
56+ instance_c . doubleView ( )
57+ console . log ( instance_c . views ( ) ) //5
0 commit comments