From bd0895a20fb02a70997a014355bef9eff105ea19 Mon Sep 17 00:00:00 2001 From: Keith Brown Date: Wed, 6 Jun 2018 17:02:45 -0700 Subject: [PATCH] Modified deepFreezeAndThrowOnMutationInDev to use Object.prototype.hasOwnProperty.call Added unit test to verify the new change allow objects with no prototype to be passed to this method without error. --- .../deepFreezeAndThrowOnMutationInDev-test.js | 7 +++++++ .../Utilities/deepFreezeAndThrowOnMutationInDev.js | 13 +++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/Libraries/Utilities/__tests__/deepFreezeAndThrowOnMutationInDev-test.js b/Libraries/Utilities/__tests__/deepFreezeAndThrowOnMutationInDev-test.js index 3ec7c7bab78bce..4b5e11ea5f37a4 100644 --- a/Libraries/Utilities/__tests__/deepFreezeAndThrowOnMutationInDev-test.js +++ b/Libraries/Utilities/__tests__/deepFreezeAndThrowOnMutationInDev-test.js @@ -26,6 +26,13 @@ describe('deepFreezeAndThrowOnMutationInDev', function() { expect(() => deepFreezeAndThrowOnMutationInDev()).not.toThrow(); }); + it('should not throw on object without prototype', () => { + __DEV__ = true; + var o = Object.create(null); + o.key = 'Value'; + expect(() => deepFreezeAndThrowOnMutationInDev(o)).not.toThrow(); + }); + it('should throw on mutation in dev with strict', () => { 'use strict'; __DEV__ = true; diff --git a/Libraries/Utilities/deepFreezeAndThrowOnMutationInDev.js b/Libraries/Utilities/deepFreezeAndThrowOnMutationInDev.js index 71a29584a35870..2e2c4952ee0acf 100644 --- a/Libraries/Utilities/deepFreezeAndThrowOnMutationInDev.js +++ b/Libraries/Utilities/deepFreezeAndThrowOnMutationInDev.js @@ -39,12 +39,17 @@ function deepFreezeAndThrowOnMutationInDev(object: T): T { } const keys = Object.keys(object); + const hasOwnProperty = Object.prototype.hasOwnProperty; for (var i = 0; i < keys.length; i++) { var key = keys[i]; - if (object.hasOwnProperty(key)) { - object.__defineGetter__(key, identity.bind(null, object[key])); - object.__defineSetter__(key, throwOnImmutableMutation.bind(null, key)); + if (hasOwnProperty.call(object, key)) { + Object.defineProperty(object, key, { + get: identity.bind(null, object[key]), + }); + Object.defineProperty(object, key, { + set: throwOnImmutableMutation.bind(null, key), + }); } } @@ -53,7 +58,7 @@ function deepFreezeAndThrowOnMutationInDev(object: T): T { for (var i = 0; i < keys.length; i++) { var key = keys[i]; - if (object.hasOwnProperty(key)) { + if (hasOwnProperty.call(object, key)) { deepFreezeAndThrowOnMutationInDev(object[key]); } }