From 459ad9552600b329a1454d79817b7b57f663d427 Mon Sep 17 00:00:00 2001 From: Jukka Kurkela Date: Wed, 20 May 2020 17:05:22 +0300 Subject: [PATCH] Preserve object prototypes when cloning --- src/helpers/helpers.core.js | 2 +- test/specs/helpers.core.tests.js | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/helpers/helpers.core.js b/src/helpers/helpers.core.js index ffcc0eae38a..0e5ad2a4b4c 100644 --- a/src/helpers/helpers.core.js +++ b/src/helpers/helpers.core.js @@ -199,7 +199,7 @@ export function clone(source) { } if (isObject(source)) { - const target = {}; + const target = Object.create(source); const keys = Object.keys(source); const klen = keys.length; let k = 0; diff --git a/test/specs/helpers.core.tests.js b/test/specs/helpers.core.tests.js index 869e9dfd182..2586173e789 100644 --- a/test/specs/helpers.core.tests.js +++ b/test/specs/helpers.core.tests.js @@ -360,6 +360,27 @@ describe('Chart.helpers.core', function() { expect(output.o).not.toBe(o0); expect(output.o.a).not.toBe(a1); }); + it('should preserve prototype of objects', function() { + // https://github.com/chartjs/Chart.js/issues/7340 + class MyConfigObject { + constructor(s) { + this._s = s; + } + func() { + return 10; + } + } + var original = new MyConfigObject('something'); + var output = helpers.merge({}, { + plugins: [{ + test: original + }] + }); + var clone = output.plugins[0].test; + expect(clone).toBeInstanceOf(MyConfigObject); + expect(clone).toEqual(original); + expect(clone === original).toBeFalse(); + }); }); describe('mergeIf', function() {