Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for obscure bug when running in VM #12

Merged
merged 2 commits into from
Nov 25, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -39,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 = {};
Expand Down Expand Up @@ -83,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 = {};
Expand Down
11 changes: 11 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}