'How to detect if a member of a class was invoked inside or outside of that class?
My JavaScript protected member implementation for a Super class (lines 3-47) below uses # (lines 4-5) to make private members, $ (lines 4-5) as a protected member marker, and returns a Proxy object (lines 10-45) inside the Super class constructor to dynamically handle any protected member access.
The protected members of Super class are inherited in my Sub class (lines 49-59), but the problem is, these protected members are also accessible outside of the class (lines 65-66, 74-75, 81-82) because I am unable to detect in lines 14 and 30 if these protected members were invoked inside or outside of the class.
So, in this context, how to detect if a member of a class was invoked inside or outside of that class?
JavaScript Code
1 'use strict';
2
3 class Super {
4 #$fieldActualProtected = 0;
5 #$methodActualProtected() {
6 console.log('__methodActualProtected()__');
7 }
8
9 constructor() {
10 const target = this;
11 const handler =
12 {
13 get(target, key, receiver) {
14 if (key[0] === '$') {
15 let member;
16
17 try {
18 member = eval(`target.#${key}`);
19 }
20 finally {
21 // Nothing here, just syntax requirement
22 }
23
24 return member;
25 }
26
27 return Reflect.get(...arguments);
28 },
29 set(target, key, value, receiver) {
30 if (key[0] === '$') {
31 try {
32 eval(`target.#${key} = ${value}`);
33 }
34 finally {
35 // Nothing here, just syntax requirement
36 }
37
38 return true;
39 }
40
41 return Reflect.set(...arguments);
42 },
43 };
44
45 return new Proxy(target, handler);
46 }
47 }
48
49 class Sub extends Super {
50 constructor() {
51 super();
52 }
53
54 subMethod(value) {
55 this.$fieldActualProtected = value;
56 console.log(this.$fieldActualProtected);
57 this.$methodActualProtected();
58 }
59 }
60
61 console.dir(Super);
62 console.group(`SUP_OBJECT`);
63 let sup = new Super();
64 console.dir(sup);
65 // sup.$fieldActualProtected = 1;
66 // sup.$methodActualProtected();
67 console.groupEnd();
68
69 console.dir(Sub);
70 console.group(`SUB1_OBJECT`);
71 let sub1 = new Sub();
72 console.dir(sub1);
73 sub1.subMethod(2);
74 // console.log(sub1.$fieldActualProtected);
75 // console.log(sub1.$methodActualProtected);
76 console.groupEnd();
77 console.group(`SUB2_OBJECT`);
78 let sub2 = new Sub();
79 console.dir(sub2);
80 sub2.subMethod(3);
81 // console.log(sub2.$fieldActualProtected);
82 // console.log(sub2.$methodActualProtected);
83 console.groupEnd();
Console Output ![Console output of the JavaScript code] (https://i.stack.imgur.com/tn6FC.png)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
