Friday 24 February 2017

Add private scope to javascript objects and classes

http://ift.tt/2lBsO3S is mostly a proof of concept I made for fun as it uses several frowned upon techniques such as decorating Object.prototype, stack inspection and Function.caller, which isn't even supported in strict mode.Nevertheless, my goal was to bolt on private scoping into any regular javascript object, without any need for precompiling.The end result is that you just include this module require('private-scope') and now can do things like so:const test = { getX: function() { return this.private.x; }, setX: function(x) { this.private.x = x; } }; test.private.x = 5; // TypeError: cannot find x of undefined test.setX(100); console.log(test.private.x); // TypeError: cannot find x of undefined console.log(test.getX()); // 100

Submitted February 24, 2017 at 05:07PM by Macmee

No comments:

Post a Comment