From e24365a13324a96d26669d6e04f8e367ae2512e2 Mon Sep 17 00:00:00 2001 From: Dan MacTough Date: Wed, 21 Nov 2012 12:11:13 -0500 Subject: [PATCH 1/2] Use local i within _clone function instead of outer closure i. --- clone.js | 1 + 1 file changed, 1 insertion(+) diff --git a/clone.js b/clone.js index 9582af5..e630b57 100644 --- a/clone.js +++ b/clone.js @@ -23,6 +23,7 @@ function clone(parent, circular) { var circularResolved = {}; var circularReplace = []; function _clone(parent, context, child, cIndex) { + var i; // Use local context within this function // Deep clone all properties of parent into child if (typeof parent == 'object') { if (parent == null) From 7b23d02c029dd3d9149b0e038dfbe5f114626db9 Mon Sep 17 00:00:00 2001 From: Dan MacTough Date: Wed, 21 Nov 2012 12:16:02 -0500 Subject: [PATCH 2/2] Fix to work when running in another vm context. Includes new test. It seems that vm.runInContext() causes the "instanceof" tests to fail. Let's use more reliable .constructor.name tests, instead. --- clone.js | 12 ++++++------ test.js | 11 +++++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/clone.js b/clone.js index e630b57..f16ee34 100644 --- a/clone.js +++ b/clone.js @@ -40,14 +40,14 @@ function clone(parent, circular) { // Add to list of all parent objects circularParent[context] = parent; // Now continue cloning... - if (parent instanceof Array) { + if (parent.constructor.name === 'Array') { child = []; for(i in parent) child[i] = _clone(parent[i], context + '[' + i + ']', child, i); } - else if (parent instanceof Date) + else if (parent.constructor.name === 'Date') child = new Date(parent.getTime()); - else if (parent instanceof RegExp) + else if (parent.constructor.name === 'RegExp') child = new RegExp(parent.source); else { child = {}; @@ -84,14 +84,14 @@ function clone(parent, circular) { if (typeof parent == 'object') { if (parent == null) return parent; - if (parent instanceof Array) { + if (parent.constructor.name === 'Array') { child = []; for(i in parent) child[i] = clone(parent[i], circular); } - else if (parent instanceof Date) + else if (parent.constructor.name === 'Date') child = new Date(parent.getTime() ); - else if (parent instanceof RegExp) + else if (parent.constructor.name === 'RegExp') child = new RegExp(parent.source); else { child = {}; diff --git a/test.js b/test.js index 340992a..115b974 100644 --- a/test.js +++ b/test.js @@ -158,3 +158,14 @@ exports['clonePrototype'] = function(test) { test.done(); } + +exports['cloneWithinNewVMContext'] = function(test) { + var vm = require('vm'); + var ctx = vm.createContext({ clone: clone }); + var script = "clone( {array: [1, 2, 3], date: new Date(), regex: /^foo$/ig} );"; + var results = vm.runInContext(script, ctx); + test.ok(results.array instanceof Array); + test.ok(results.date instanceof Date); + test.ok(results.regex instanceof RegExp); + test.done(); +}