What is this?
This module gives javacript objects a private only scope.
Examples
Regular JavaScript objects:
; const test = { return thisprivatex; } { thisprivatex = x; }; testprivatex = 5; // TypeError: cannot find x of undefinedtest;console; // TypeError: cannot find x of undefinedconsole; // 100
Classes:
; { return thisprivatex; } { thisprivatex = x; } { thisprivatey = 2; }; const test = ;testprivatex = 5; // TypeError: cannot find x of undefinedtest;console; // TypeError: cannot find x of undefinedconsole; // 100
Prototypes:
; { thisprivatey = 53;} TestClassprototype { return thisprivatex;} TestClassprototype { thisprivatex = x;} TestClassprototype { return thisprivatey;} const test = ;testprivatex = 5; // TypeError: cannot find x of undefinedtest;console; // TypeError: cannot find x of undefinedconsole; // 100console; // 53
Why?
Lets say you organized your object like so:
const test = private: {} { return thisprivatex; } { thisprivatex = x; } ;
Sure you can do test.getX()
and test.setX(12)
here but you can just as easily do test.private.x
and there’s nothing stopping you from doing the latter even outside of an internal function on test
such as from within getX
and setX
. After you include this module into your project, test.private.x
is not allowed.
Are You Crazy?
Probably. And my solution isn't bulletproof. This solution leverages Function.caller
behind the scenes so things can get funky when that's not available. I'm using a slight workaround for objects created via the class
keyword too (stack inspection) to determine if a caller belongs to a class due to the absence of Function.caller
in methods created using class
.