From 75b971d985a2cbdf0a3fdf245d8bd45b3c64d294 Mon Sep 17 00:00:00 2001 From: Tremayne Christ Date: Sat, 3 Sep 2016 22:58:02 +0100 Subject: [PATCH] Prevent access from other protected objects --- protect.js | 12 ++++++------ tests/tests.js | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/protect.js b/protect.js index 48caea6..bb405fd 100644 --- a/protect.js +++ b/protect.js @@ -2,15 +2,15 @@ 'use strict'; - var callDepth = 0; // Stores the call depth of the current execution - - var locked = function () { - return !callDepth; - }; - // The protect object var protect = function (_O) { + var callDepth = 0; // Stores the call depth of the current execution + + var locked = function () { + return !callDepth; + }; + var O = _O.prototype || _O; // Protect the prototype, if there is one Object.keys(O).forEach(function (key) { diff --git a/tests/tests.js b/tests/tests.js index f60ccb8..c7a8a18 100644 --- a/tests/tests.js +++ b/tests/tests.js @@ -112,6 +112,26 @@ describe('ProtectJS', function () { testObj._function = function () {}; expect(testObj._function).to.be.undefined; }); + + it('Should NOT allow PRIVATE property access from other objects', function () { + var obj2 = { + fn: function () { + return testObj._function(); + }, + prop: function () { + return testObj._number + testObj._string; + } + }; + + // Unprotected + expect(obj2.fn).to.throw(); + expect(obj2.prop()).to.be.NaN; + + // Protected + protect(obj2); + expect(obj2.fn).to.throw(); + expect(obj2.prop()).to.be.NaN; + }); }; describe('Literal Objects', function () {