My JavaScript method overloading implementation below can't access my private static method in line 10. It seems the #
symbol cannot be embedded into a string.
JavaScript Code
1 'use strict';
2
3 class MyClass {
4 static myFunction() {
5 let length = arguments.length;
6 let methodName = `#myFunction${length}`;
7
8 console.log(methodName);
9
10 if (MyClass[methodName]) {
11 return MyClass[methodName](...arguments);
12 }
13 else {
14 throw new ReferenceError();
15 }
16 }
17
18 static #myFunction0() {
19 console.log('__myFunction0__');
20 }
21
22 static #myFunction1(x) {
23 console.log('__myFunction1__');
24 }
25
26 static #myFunction2(x, y) {
27 console.log('__myFunction2__');
28 }
29 }
30
31 let x = new MyClass();
32
33 console.dir(x);
34 console.dir(MyClass);
35 console.log(MyClass.myFunction());
36 console.log(MyClass.myFunction(1));
37 console.log(MyClass.myFunction(1, 2));
Console Output ![Console output of the JavaScript code] (https://i.stack.imgur.com/dZlun.png)
Although it works if I turn all the methods into public and non-static, but I would like to hide myFunction0()
, myFunction1()
, and myFunction2()
methods without resorting to other means, for the sake of readability. Is there any way to access my private static methods inside my public static method of the same class?
Dynamic Private Property Access Solution
It works with the help of eval()
and try...catch
in lines 9-14. It even works for non-static private methods as well!
Does anybody know the performance impact in line 10?
1 'use strict';
2
3 class MyClass {
4 static myFunction() {
5 let length = arguments.length;
6 let methodName = `myFunction${length}`;
7 let method;
8
9 try {
10 method = eval(`MyClass.#${methodName};`);
11 }
12 finally {
13 // Nothing here, just syntax requirement
14 }
15
16 console.group(`CALL FROM ${methodName}`);
17 console.log(methodName);
18 console.log(method);
19 console.groupEnd(); console.log('\n');
20
21 if (method) {
22 return method(...arguments);
23 }
24 else {
25 throw new ReferenceError();
26 }
27 }
28
29 static #myFunction0() {
30 console.log('__myFunction0__');
31 }
32
33 static #myFunction1(x) {
34 console.log('__myFunction1__');
35 }
36
37 static #myFunction2(x, y) {
38 console.log('__myFunction2__');
39 }
40 }
41
42 let x = new MyClass();
43
44 console.dir(x);
45 console.dir(MyClass);
46 MyClass.myFunction();
47 MyClass.myFunction(1);
48 MyClass.myFunction(1, 2);
49 MyClass.myFunction(1, 2, 3);
Console Output ![Console output of the JavaScript code] (https://i.stack.imgur.com/DJYS6.png)