Path: csiph.com!.POSTED.208-71-239-109.cust.centrio.cz!not-for-mail From: Cezary Tomczyk Newsgroups: comp.lang.javascript Subject: Re: Cloning an object Date: Thu, 5 Jul 2018 20:37:55 +0200 Organization: csiph.com Internet News Service Message-ID: References: <1620852.VI2in3QvqR@PointedEars.de> <9909bfec-c6e7-2a4a-2a54-ec9f271691c8@PointedEars.de> <4395113.31r3eYUQgx@PointedEars.de> <506b67da-b086-3d0e-5985-d0f8214da432@PointedEars.de> Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 8bit Injection-Date: Thu, 5 Jul 2018 18:37:56 -0000 (UTC) Injection-Info: csiph.com; posting-host="208-71-239-109.cust.centrio.cz:109.239.71.208"; logging-data="20834"; mail-complaints-to="admin@kev009.com" User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:52.0) Gecko/20100101 Thunderbird/52.8.0 In-Reply-To: <506b67da-b086-3d0e-5985-d0f8214da432@PointedEars.de> Content-Language: en-US Xref: csiph.com comp.lang.javascript:35353 On 05/07/2018 19:49, Thomas 'PointedEars' Lahn wrote: > Cezary Tomczyk wrote: > >> On 04/07/2018 23:25, Thomas 'PointedEars' Lahn wrote: >>> function clone (obj, deepCopy) >>> { >>> const CLONE = Object.create(Object.getPrototypeOf(obj)); >>> >>> Object.getOwnPropertyNames(obj).forEach((name) => { >>> const DESC = Object.getOwnPropertyDescriptor(obj, name); >>> >>> if (deepCopy) >>> { >>> /* FIXME: Standardize Object.isObject() */ >>> if (("value" in DESC) >>> && (typeof DESC.value == "object") >>> && (DESC.value != null)) >>> { >>> DESC.value = clone(DESC.value); >>> } >>> } >>> >>> Object.defineProperty(CLONE, name, DESC || {}); >>> }); >>> >>> return CLONE; >>> } >>> […] >> >> It passes for simple objects, but if the property has a value as an >> array or Date object then it doesn't work. > > I agree regarding Date instances, but where is the problem with Array > instances? It doesn't create a real Array copy. Try clone following object: var o = { a: 1, b: [ { test: 'test' } ] }; var cloned = clone(o); o.b[0].test = 'something'; expect(cloned.b[0].test).toBe('test'); This test doesn't pass. Basically, modifications on original object should not modify cloned object. -- Cezary Tomczyk http://www.ctomczyk.pl/ https://www.aslint.org/